/** * Optional: Seed a default business and link all existing users to it. * Run after applying supabase/migrations/20250220000000_admin_businesses_authorizations.sql * * Load env (e.g. from .env.local) before running: * npx tsx scripts/seed-admin-default-business.ts * Or: node -r dotenv/config node_modules/.bin/tsx scripts/seed-admin-default-business.ts * (with dotenv configured to load .env.local) */ import { supabaseAdmin } from "../lib/supabase" import { businessService, userBusinessService } from "../lib/admin-authorization-service" const DEFAULT_BUSINESS_NAME = "Default" const DEFAULT_SLUG = "default" async function main() { if (!supabaseAdmin) { console.error("SUPABASE_SERVICE_ROLE_KEY is not set. Cannot run seed.") process.exit(1) } let defaultBusinessId: number const existing = await businessService.list() const defaultBusiness = existing.find((b) => b.slug === DEFAULT_SLUG) if (defaultBusiness) { console.log("Default business already exists:", defaultBusiness.business_id) defaultBusinessId = defaultBusiness.business_id } else { const created = await businessService.create({ name: DEFAULT_BUSINESS_NAME, slug: DEFAULT_SLUG }) console.log("Created default business:", created.business_id) defaultBusinessId = created.business_id } const { data: users, error: usersError } = await supabaseAdmin.from("users").select("user_id") if (usersError) { console.error("Failed to fetch users:", usersError) process.exit(1) } if (!users?.length) { console.log("No users to link.") return } const existingLinks = await userBusinessService.listByBusinessId(defaultBusinessId) const linkedIds = new Set(existingLinks.map((l) => l.user_id)) let added = 0 for (const u of users) { if (linkedIds.has(u.user_id)) continue try { await userBusinessService.add({ user_id: u.user_id, business_id: defaultBusinessId, role: null }) linkedIds.add(u.user_id) added++ } catch (e) { console.warn("Skip user", u.user_id, e) } } console.log("Linked", added, "users to default business. Total linked:", linkedIds.size) } main().catch((e) => { console.error(e) process.exit(1) })