package db
import (
"fmt"
"math/rand/v2"
"net/url"
"strconv"
"log/slog"
)
func (d *DB) CreateBusiness(personId int, f url.Values) (int, error) {
businessName := f.Get("business_name")
merchantName := "stripe"
paySchedule := f.Get("pay_schedule")
if paySchedule == "cash_annual" {
merchantName = "cash"
}
if businessName == "" || businessName == "N/A" {
businessName = fmt.Sprintf(`%s %s personal account %d`, f.Get("firstname"), f.Get("lastname"), rand.Int())
}
createBusinessSql := `WITH zero_tier AS (SELECT id FROM business_tier WHERE name = 'zero'),
merchants AS (SELECT id,name FROM merchant)
INSERT INTO business
(business_tier_id, name, current_merchant_id,
address_line1, address_line2, address_state, address_city, address_postal_code, address_country
) VALUES
(
(SELECT id FROM business_tier), $1, (SELECT id FROM merchants WHERE name = $2),
$3, $4, $5, $6, $7, $8
)
RETURNING id;`
args := []any{
businessName, merchantName,
f.Get("address_line1"), f.Get("address_line2"), f.Get("address_city"),
f.Get("address_state"), f.Get("address_postal_code"), f.Get("address_country"),
}
slog.Info("creating business via", append([]any{"sql", createBusinessSql}, asLogArgs(args)...)...)
tx, err := d.db.Begin()
if err != nil {
return 0, err
}
row := tx.QueryRow(createBusinessSql, args...)
var businessId int
err = row.Scan(&businessId)
if err != nil {
return 0, err
}
personBusinessSql := `INSERT INTO person_business (person_id, business_id) VALUES ($1, $2) RETURNING true;`
row = tx.QueryRow(personBusinessSql, personId, businessId)
var ok int
err = row.Scan(&ok)
if err != nil {
return 0, err
}
if err := tx.Commit(); err != nil {
return 0, err
}
return businessId, nil
}
func asLogArgs(xs []any) []any {
intercalated := []any{}
for i, x := range xs {
intercalated = append(intercalated, strconv.Itoa(i+1), x)
}
return intercalated
}