/**
 * First-run seeding.
 *  - Always: the seven default system roles (AUTH-001).
 *  - If SEED_ADMIN_EMAIL + SEED_ADMIN_PASSWORD are set and no users exist: the agency, first workspace and admin.
 *  - If SEED_DEMO=true (default for local PGlite): a complete real-estate demo workspace with sandbox integrations,
 *    so every module can be tested end to end before real provider credentials are added.
 * Without seeded users, /setup creates the agency and first admin from the browser.
 */
import { eq, isNull, sql } from "drizzle-orm";
import bcrypt from "bcryptjs";
import * as schema from "./schema";
import type { DB } from "./index";
import { DEFAULT_ROLES } from "@/lib/rbac";
import type { Ctx } from "@/lib/auth";
import { randomToken, isoDay } from "@/lib/util";
import { industryStages } from "@/lib/industry";

export const DEFAULT_STAGES: schema.PipelineStage[] = [
  { id: "new", name: "New", order: 0, probability: 5, kind: "open", conversionEvent: undefined },
  { id: "contacted", name: "Contacted", order: 1, probability: 10, kind: "open" },
  { id: "qualified", name: "Qualified", order: 2, probability: 25, kind: "open", conversionEvent: "Qualified" },
  { id: "site_visit", name: "Site Visit", order: 3, probability: 50, kind: "open", conversionEvent: "SiteVisit" },
  { id: "negotiation", name: "Negotiation", order: 4, probability: 75, kind: "open" },
  { id: "won", name: "Won (Booked)", order: 5, probability: 100, kind: "won", conversionEvent: "Won" },
  { id: "lost", name: "Lost", order: 6, probability: 0, kind: "lost" },
];

/** Default funnel for the workspace's industry (stable ids; see lib/industry.ts). */
export const defaultStages = (industry = "general"): schema.PipelineStage[] => industryStages(industry);

export async function ensureSystemRoles(db: DB) {
  const existing = await db.select().from(schema.roles).where(isNull(schema.roles.workspaceId));
  for (const r of DEFAULT_ROLES) {
    const cur = existing.find((e) => e.key === r.key);
    if (!cur) await db.insert(schema.roles).values({ key: r.key, name: r.name, permissions: r.permissions, isSystem: true });
    // new capabilities added in later modules are merged into existing system roles (existing values untouched)
    else if (Object.keys(r.permissions).some((k) => !(k in cur.permissions))) await db.update(schema.roles).set({ permissions: { ...r.permissions, ...cur.permissions } }).where(eq(schema.roles.id, cur.id));
  }
  // custom roles get the new social capabilities from the default they most resemble (none granted by default)
  const custom = await db.select().from(schema.roles).where(sql`${schema.roles.workspaceId} IS NOT NULL`);
  for (const r of custom) if (!("social" in r.permissions)) await db.update(schema.roles).set({ permissions: { social: "", social_moderate: "", social_rules: "", social_ai: "", social_analytics: "", ...r.permissions } }).where(eq(schema.roles.id, r.id));
}

export async function systemRole(db: DB, key: string) {
  const r = await db.query.roles.findFirst({ where: (t, { and, eq, isNull }) => and(eq(t.key, key), isNull(t.workspaceId)) });
  if (!r) throw new Error(`Missing system role ${key}`);
  return r;
}

/** Creates the agency + first workspace + default pipeline. Used by /setup and seeding. */
export async function createAgencyWorkspace(db: DB, input: { agencyName: string; workspaceName: string; timezone?: string; currency?: string; locale?: string; industry?: string; starters?: boolean }) {
  const [agency] = await db.insert(schema.agencies).values({ name: input.agencyName, branding: { productName: "Tempest Pulse", primaryColor: "#2563EB" } }).returning();
  const ws = await createWorkspace(db, agency!.id, input.workspaceName, input.timezone, input.currency, input.locale, input.industry, { starters: input.starters });
  return { agency: agency!, workspace: ws };
}

export async function createWorkspace(db: DB, agencyId: string | null, name: string, timezone = "Asia/Dhaka", currency = "BDT", locale = "en", industry = "general", opts: { starters?: boolean } = {}) {
  const base = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "workspace";
  let slug = base;
  for (let i = 2; await db.query.workspaces.findFirst({ where: eq(schema.workspaces.slug, slug) }); i++) slug = `${base}-${i}`;
  const [ws] = await db.insert(schema.workspaces).values({
    agencyId, name, slug, hookKey: randomToken(16), timezone, currency, locale,
    settings: { quietHours: { enabled: true, start: "21:00", end: "09:00" }, frequencyCap: { enabled: true, perDay: 3 }, attributionModel: "last_touch", pacingThresholdPct: 15, anomalyThresholdPct: 40, defaultCountryCode: currency === "AUD" ? "61" : currency === "USD" ? "1" : "880", sessionTimeoutMinutes: 60 * 24 * 7, industry },
  }).returning();
  // industry funnel, lead fields, starter knowledge base & saved replies, SLA and AI defaults
  const { applyIndustry } = await import("@/lib/services/industry");
  await applyIndustry(db, ws!.id, industry, { pipeline: true, starters: opts.starters ?? true });
  return (await db.query.workspaces.findFirst({ where: eq(schema.workspaces.id, ws!.id) }))!;
}

export async function ensureSeeded(db: DB) {
  await ensureSystemRoles(db);
  const [{ n }] = (await db.select({ n: sql<number>`count(*)::int` }).from(schema.users)) as [{ n: number }];
  if (n > 0) return;
  const email = process.env.SEED_ADMIN_EMAIL;
  const password = process.env.SEED_ADMIN_PASSWORD;
  const demo = process.env.SEED_DEMO ? process.env.SEED_DEMO === "true" : !process.env.DATABASE_URL;
  if (!demo && !(email && password)) return; // → /setup
  const { agency, workspace } = await createAgencyWorkspace(db, { agencyName: "Brand Tempest", workspaceName: demo ? "ACE Developers" : process.env.SEED_WORKSPACE_NAME ?? "My Workspace", industry: demo ? "real_estate" : process.env.SEED_INDUSTRY ?? "general", starters: !demo });
  const admin = await createUser(db, { email: email ?? "admin@brandtempest.com", name: "Arafat Riad", password: password ?? process.env.SEED_DEMO_PASSWORD ?? "TempestDemo2026!", agencyId: agency.id, isAgencyAdmin: true });
  await db.insert(schema.memberships).values({ workspaceId: workspace.id, userId: admin.id, roleId: (await systemRole(db, "workspace_admin")).id });
  if (demo) await db.update(schema.workspaces).set({ plan: "enterprise" }).where(eq(schema.workspaces.id, workspace.id)); // demo shows every feature
  if (demo) await seedDemo(db, workspace, admin.id).catch((e) => console.error("[seed] demo data failed", e));
}

export async function createUser(db: DB, u: { email: string; name: string; password?: string; agencyId?: string | null; isAgencyAdmin?: boolean; status?: string }) {
  const [row] = await db.insert(schema.users).values({
    email: u.email.toLowerCase().trim(), name: u.name, passwordHash: u.password ? await bcrypt.hash(u.password, 11) : null,
    agencyId: u.agencyId ?? null, isAgencyAdmin: !!u.isAgencyAdmin, status: u.status ?? "active",
  }).returning();
  return row!;
}

/* ------------------------------------------------------------------ */
/* Demo data: a real-estate developer running Meta + Google lead gen   */
/* ------------------------------------------------------------------ */

async function seedDemo(db: DB, workspace: typeof schema.workspaces.$inferSelect, adminId: string) {
  const pw = process.env.SEED_DEMO_PASSWORD ?? "TempestDemo2026!";
  const ctx: Ctx = { db, workspace, user: null, perms: DEFAULT_ROLES[1]!.permissions, roleKey: "system", roleName: "System", actor: { type: "system", id: null, name: "Seed" } };
  const ws = workspace.id;
  const people: [string, string, string, string?, string[]?][] = [
    ["Nusrat Jahan", "manager@brandtempest.com", "marketing_manager"],
    ["Tanvir Ahmed", "performance@brandtempest.com", "performance"],
    ["Sadia Islam", "content@brandtempest.com", "content"],
    ["Rafiq Hasan", "rafiq@acedevelopers.com", "sales_rep", "Gulshan", ["Gulshan Heights"]],
    ["Mitu Akter", "mitu@acedevelopers.com", "sales_rep", "Bashundhara", ["Bashundhara Residency"]],
    ["Imran Chowdhury", "imran@acedevelopers.com", "sales_rep", "Uttara", ["Uttara Greens"]],
    ["ACE Client", "client@acedevelopers.com", "client_viewer"],
  ];
  const users: Record<string, string> = {};
  for (const [name, email, role, territory, projects] of people) {
    const u = await createUser(db, { email, name, password: pw });
    users[role === "sales_rep" ? name : role] = u.id;
    await db.insert(schema.memberships).values({ workspaceId: ws, userId: u.id, roleId: (await systemRole(db, role)).id, territory: territory ?? null, projects: projects ?? [] });
  }
  const reps = [users["Rafiq Hasan"]!, users["Mitu Akter"]!, users["Imran Chowdhury"]!];

  await db.insert(schema.routingRules).values([
    { workspaceId: ws, name: "Gulshan Heights → Rafiq", priority: 10, strategy: "project", match: { project: "Gulshan Heights" }, userIds: [reps[0]!] },
    { workspaceId: ws, name: "Bashundhara Residency → Mitu", priority: 20, strategy: "project", match: { project: "Bashundhara Residency" }, userIds: [reps[1]!] },
    { workspaceId: ws, name: "Everything else – round robin", priority: 100, strategy: "round_robin", match: {}, userIds: reps },
  ]);
  await db.insert(schema.customFieldDefs).values([
    { workspaceId: ws, key: "budget", label: "Budget", type: "dropdown", options: ["< 1 Cr", "1–2 Cr", "2–3 Cr", "3 Cr +"] },
    { workspaceId: ws, key: "location", label: "Preferred location", type: "text" },
    { workspaceId: ws, key: "timeline", label: "Purchase timeline", type: "dropdown", options: ["Immediately", "Within 3 months", "3–6 months", "6–12 months"] },
    { workspaceId: ws, key: "unit_type", label: "Unit type", type: "multiselect", options: ["2 bed", "3 bed", "4 bed", "Duplex", "Commercial"] },
    { workspaceId: ws, key: "handover_date", label: "Handover date", type: "date" },
  ]).onConflictDoNothing();
  const [propDef] = await db.insert(schema.customObjectDefs).values({ workspaceId: ws, key: "property", label: "Property / Unit", fields: [{ key: "project", label: "Project", type: "text" }, { key: "unit", label: "Unit no.", type: "text" }, { key: "size_sqft", label: "Size (sqft)", type: "number" }, { key: "price", label: "Price (BDT)", type: "number" }, { key: "status", label: "Status", type: "dropdown", options: ["Available", "Held", "Booked"] }] }).returning();

  // sandbox integrations (switch to live by reconnecting with real credentials)
  const { writeSecret } = await import("@/lib/vault");
  const integ = async (provider: string, displayName: string, accountRef: string, config: Record<string, unknown> = {}) => {
    const tokenRef = await writeSecret(db, ws, { sandbox: "true" });
    const [i] = await db.insert(schema.integrations).values({ workspaceId: ws, provider, displayName, accountRef, config, tokenRef, mode: "sandbox", status: "connected", lastSyncAt: new Date() }).returning();
    return i!;
  };
  const meta = await integ("meta", "ACE Developers (sandbox)", "act_100200300", { adAccountId: "act_100200300", pixelId: "880123456789", pageId: "1122334455", backfillDays: 45 });
  const google = await integ("google_ads", "Google Ads 123-456-7890 (sandbox)", "1234567890", { customerId: "123-456-7890", conversionActionQualified: "111", conversionActionWon: "222", conversionActionSiteVisit: "333", backfillDays: 45 });
  await integ("whatsapp", "ACE Developers WhatsApp (sandbox)", "1098765432", { phoneNumberId: "1098765432", wabaId: "2345678901" });
  await integ("bd_sms", "BD SMS · ACE DEV (sandbox)", "ACE DEV", { senderId: "ACE DEV", endpoint: "https://sms.example.com/api?api_key={apiKey}&senderid={sender}&number={to}&message={message}&type={type}" });
  await integ("ses", "SES · hello@acedevelopers.com (sandbox)", "hello@acedevelopers.com", { region: "ap-southeast-1", fromEmail: "hello@acedevelopers.com" });
  await integ("google_calendar", "Google Calendar (sandbox)", "primary", { calendarId: "primary" });
  await integ("sslcommerz", "SSLCommerz (sandbox)", "testbox", { storeId: "testbox", sandbox: "true" });
  await integ("bkash", "bKash (sandbox)", "sandbox", { appKey: "sandbox", username: "sandbox", sandbox: "true" });
  await integ("stripe", "Stripe (test mode)", "acct_test", {});
  const ga4 = await integ("ga4", "GA4 property 987654 (sandbox)", "987654", { propertyId: "987654" });
  const gsc = await integ("search_console", "sc-domain:acedevelopers.com (sandbox)", "sc-domain:acedevelopers.com", { siteUrl: "sc-domain:acedevelopers.com" });
  const { syncIntegration } = await import("@/connectors");
  await syncIntegration(ctx, meta);
  await syncIntegration(ctx, google);
  await syncIntegration(ctx, ga4);
  await syncIntegration(ctx, gsc);
  await db.update(schema.adAccounts).set({ monthlyBudget: 60000000 }).where(eq(schema.adAccounts.provider, "meta"));
  await db.update(schema.adAccounts).set({ monthlyBudget: 30000000 }).where(eq(schema.adAccounts.provider, "google"));

  // templates
  await db.insert(schema.templates).values([
    { workspaceId: ws, channel: "whatsapp", name: "welcome_enquiry", language: "en", body: "Hi {{first_name|there}}, thank you for your interest in {{project|our projects}}! I'm {{owner_name|your advisor}} from ACE Developers. When is a good time for a quick call?", variables: ["first_name", "project", "owner_name"], providerStatus: "approved", category: "marketing" },
    { workspaceId: ws, channel: "whatsapp", name: "site_visit_reminder", language: "bn", body: "প্রিয় {{first_name|গ্রাহক}}, আগামীকাল {{project|প্রকল্প}} সাইট ভিজিটের কথা মনে করিয়ে দিচ্ছি। যেকোনো প্রশ্নে এই নম্বরে উত্তর দিন।", variables: ["first_name", "project"], providerStatus: "approved", category: "utility" },
    { workspaceId: ws, channel: "whatsapp", name: "reengage_offer", language: "en", body: "Hi {{first_name|there}}, limited units left at {{project|Gulshan Heights}} with a festive booking offer. Reply YES to get the price sheet.", variables: ["first_name", "project"], providerStatus: "pending", category: "marketing" },
    { workspaceId: ws, channel: "email", name: "Brochure follow-up", language: "en", subject: "Your {{project|ACE}} brochure", body: "Dear {{first_name|there}},\n\nThank you for visiting us. Please find the brochure and floor plans for {{project|our project}} here: https://acedevelopers.com/brochure\n\nWarm regards,\n{{owner_name|ACE Developers}}", variables: ["first_name", "project", "owner_name"], providerStatus: "approved" },
    { workspaceId: ws, channel: "sms", name: "Bangla call-back", language: "bn", body: "ACE Developers: {{first_name|}} আপনার আগ্রহের জন্য ধন্যবাদ। আমাদের প্রতিনিধি শীঘ্রই কল করবেন। STOP লিখে বন্ধ করুন।", variables: ["first_name"], providerStatus: "approved" },
  ]);
  await db.insert(schema.cannedReplies).values([
    { workspaceId: ws, shortcut: "/price", body: "Thanks for asking! Prices depend on floor and size — may I share the latest price sheet on WhatsApp?" },
    { workspaceId: ws, shortcut: "/visit", body: "We'd love to show you the site. Which day suits you this week — we have slots from 10am to 6pm." },
    { workspaceId: ws, shortcut: "/loan", body: "We partner with leading banks for home loans up to 70%. I can connect you with our loan desk." },
  ]);
  await db.insert(schema.brandKits).values({ workspaceId: ws, name: "ACE Developers", colors: ["#2563EB", "#000000", "#F7F7FA", "#7C6CF0"], fonts: ["Syne", "Kanit", "Inter Tight"], logos: [], voice: "Premium yet approachable. Speak to families and NRB investors about trust, location and on-time handover. Avoid hype and unverifiable claims." });
  await db.insert(schema.assets).values([
    { workspaceId: ws, type: "image", name: "Gulshan Heights facade", url: "https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?w=800", folder: "Gulshan Heights", tags: ["exterior", "hero"] },
    { workspaceId: ws, type: "image", name: "Living room render", url: "https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?w=800", folder: "Gulshan Heights", tags: ["interior"] },
    { workspaceId: ws, type: "image", name: "Bashundhara aerial", url: "https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?w=800", folder: "Bashundhara Residency", tags: ["aerial"] },
  ]);

  // leads over the last 45 days, attributed to the sandbox campaigns
  const firstNames = ["Rahim", "Karim", "Farhana", "Shakil", "Nadia", "Jamal", "Ayesha", "Mahmud", "Rumana", "Sohel", "Tahmina", "Arif", "Lamia", "Habib", "Shirin", "Kamrul", "Fahim", "Rina", "Zahid", "Mehnaz", "Asif", "Tania", "Rubel", "Sharmin", "Nayeem"];
  const lastNames = ["Hossain", "Rahman", "Ahmed", "Chowdhury", "Islam", "Khan", "Sarkar", "Uddin", "Akter", "Siddiqui", "Haque", "Karim"];
  const projects = ["Gulshan Heights", "Bashundhara Residency", "Uttara Greens"];
  const cities = ["Dhaka", "Dhaka", "Dhaka", "Chattogram", "Sylhet"];
  const sources: { channel: string; campaign?: string; adset?: string; ad?: string; utm?: string }[] = [
    { channel: "meta_lead_ad", campaign: "meta-c0", adset: "meta-c0-s0", ad: "meta-0-0-0" }, { channel: "meta_lead_ad", campaign: "meta-c0", adset: "meta-c0-s1", ad: "meta-0-1-1" },
    { channel: "meta_lead_ad", campaign: "meta-c1", adset: "meta-c1-s0", ad: "meta-1-0-0" }, { channel: "meta_lead_ad", campaign: "meta-c1", adset: "meta-c1-s1", ad: "meta-1-1-0" },
    { channel: "web_form", campaign: "google-c0", adset: "google-c0-s0", utm: "google" }, { channel: "google_lead_form", campaign: "google-c1", adset: "google-c1-s0" },
    { channel: "whatsapp" }, { channel: "web_form", utm: "organic" }, { channel: "call" },
  ];
  const { captureLead, changeStage, createActivity } = await import("@/lib/services/leads");
  const { setConsent } = await import("@/lib/services/contacts");
  let seed = 7;
  const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
  const pick = <T,>(a: T[]) => a[Math.floor(rnd() * a.length)]!;
  const reasons = ["Budget mismatch", "Bought elsewhere", "Location not suitable", "Not reachable", "Timeline too long"];
  const sysCtx = { ...ctx, perms: { ...ctx.perms, contacts: "C" as const } };
  for (let i = 0; i < 140; i++) {
    const daysAgo = Math.floor(rnd() * 44) + 1;
    const at = new Date(Date.now() - daysAgo * 86400000 - Math.floor(rnd() * 36000000));
    const fn = pick(firstNames), ln = pick(lastNames);
    const src = pick(sources);
    const project = src.campaign?.startsWith("meta-c1") ? "Bashundhara Residency" : src.campaign?.startsWith("meta-c0") ? "Gulshan Heights" : pick(projects);
    const phone = `017${String(10000000 + Math.floor(rnd() * 89999999)).slice(0, 8)}`;
    const r = await captureLead(sysCtx, {
      firstName: fn, lastName: ln, phone, email: rnd() > 0.35 ? `${fn.toLowerCase()}.${ln.toLowerCase()}${i}@example.com` : undefined, city: pick(cities), project,
      customFields: rnd() > 0.4 ? { budget: pick(["< 1 Cr", "1–2 Cr", "2–3 Cr", "3 Cr +"]), timeline: pick(["Immediately", "Within 3 months", "3–6 months"]), location: project.split(" ")[0] } : {},
      attribution: { channel: src.channel, campaignId: src.campaign, adsetId: src.adset, adId: src.ad, utmSource: src.utm ?? (src.channel.startsWith("meta") ? "facebook" : undefined), utmMedium: src.campaign ? "paid" : undefined, utmCampaign: src.campaign, fbclid: src.channel.startsWith("meta") ? `IwAR${randomToken(10)}` : undefined, gclid: src.campaign?.startsWith("google") ? `Cj0K${randomToken(10)}` : undefined },
    });
    const c = r.contact;
    const deal = r.deal!;
    await db.update(schema.contacts).set({ createdAt: at, updatedAt: at, lastActivityAt: at }).where(eq(schema.contacts.id, c.id));
    await db.update(schema.leadSources).set({ capturedAt: at, createdAt: at }).where(eq(schema.leadSources.contactId, c.id));
    await db.update(schema.events).set({ occurredAt: at, createdAt: at }).where(eq(schema.events.contactId, c.id));
    await setConsent(ctx, c.id, "whatsapp", "opted_in", src.channel);
    if (rnd() > 0.92) await setConsent(ctx, c.id, "sms", "opted_out", "sms keyword");
    // progress through the funnel
    const p = rnd();
    const path = p < 0.18 ? ["new"] : p < 0.4 ? ["contacted"] : p < 0.58 ? ["contacted", "qualified"] : p < 0.72 ? ["contacted", "qualified", "site_visit"] : p < 0.8 ? ["contacted", "qualified", "site_visit", "negotiation"] : p < 0.88 ? ["contacted", "qualified", "site_visit", "negotiation", "won"] : ["contacted", "lost"];
    let t = at.getTime();
    for (const st of path) {
      if (st === "new") continue;
      t += Math.floor(rnd() * 3 * 86400000) + 3 * 60000;
      if (t > Date.now()) break;
      const value = st === "won" ? Math.round((8000000 + rnd() * 22000000)) * 100 : undefined;
      await changeStage(sysCtx, deal.id, st, { lostReason: st === "lost" ? pick(reasons) : undefined, value });
      await db.update(schema.deals).set({ stageChangedAt: new Date(t), ...(st === "won" ? { wonAt: new Date(t) } : {}), ...(st === "lost" ? { lostAt: new Date(t) } : {}) }).where(eq(schema.deals.id, deal.id));
      if (st === "contacted") {
        const firstTouch = new Date(at.getTime() + Math.floor(rnd() * (rnd() > 0.6 ? 4 : 90)) * 60000 + 60000);
        await db.update(schema.contacts).set({ firstContactedAt: firstTouch }).where(eq(schema.contacts.id, c.id));
        const a = await createActivity(sysCtx, { contactId: c.id, dealId: deal.id, userId: c.ownerId, type: "call", title: "Intro call", body: "Discussed requirements and budget.", outcome: "connected", durationSec: 180 + Math.floor(rnd() * 400), completed: true });
        await db.update(schema.activities).set({ createdAt: firstTouch, completedAt: firstTouch }).where(eq(schema.activities.id, a.id));
      }
      if (st === "site_visit") {
        const a = await createActivity(sysCtx, { contactId: c.id, dealId: deal.id, userId: c.ownerId, type: "visit", title: `Site visit – ${project}`, outcome: "visited", completed: true });
        await db.update(schema.activities).set({ createdAt: new Date(t), completedAt: new Date(t) }).where(eq(schema.activities.id, a.id));
      }
    }
    await db.update(schema.events).set({ occurredAt: sql`LEAST(${schema.events.occurredAt}, now())` }).where(eq(schema.events.contactId, c.id));
    if (path.length < 3 && rnd() > 0.5) await createActivity(sysCtx, { contactId: c.id, dealId: deal.id, userId: c.ownerId, type: pick(["call", "meeting", "visit", "task"]), title: pick(["Follow-up call", "Send price sheet", "Schedule site visit", "Share brochure"]), dueAt: new Date(Date.now() + (rnd() - 0.3) * 4 * 86400000) });
    if (i % 3 === 0) {
      const [conv] = await db.insert(schema.conversations).values({ workspaceId: ws, contactId: c.id, channel: pick(["whatsapp", "whatsapp", "messenger", "sms", "email"]), assigneeId: c.ownerId, status: pick(["open", "open", "pending", "closed"]), unread: Math.floor(rnd() * 3), lastMessageAt: new Date(Date.now() - Math.floor(rnd() * 3 * 86400000)) }).returning().onConflictDoNothing();
      if (conv) {
        const lines: [string, string][] = [["in", `Hi, I saw the ad for ${project}. What is the price for a 3 bed?`], ["out", `Hello ${fn}! Thanks for reaching out. 3 bed units at ${project} start from 1.8 Cr. Would you like to visit the site this week?`], ["in", pick(["Saturday afternoon works.", "Can you share the floor plan first?", "আমি শুক্রবার আসতে পারব।", "Is there a home loan option?"])]];
        for (const [k, [dir, body]] of lines.entries()) await db.insert(schema.messages).values({ workspaceId: ws, conversationId: conv.id, direction: dir, channel: conv.channel, body, status: dir === "in" ? "received" : "read", createdAt: new Date(conv.lastMessageAt.getTime() - (lines.length - k) * 600000) });
      }
    }
  }

  // property records linked to won deals
  const won = await db.select().from(schema.deals).where(sql`${schema.deals.workspaceId} = ${ws} AND ${schema.deals.wonAt} IS NOT NULL`);
  for (const [k, d] of won.entries()) await db.insert(schema.customObjectRecords).values({ workspaceId: ws, objectDefId: propDef!.id, contactId: d.contactId, data: { project: d.project, unit: `${String.fromCharCode(65 + (k % 6))}-${(k % 12) + 2}0${(k % 4) + 1}`, size_sqft: 1450 + (k % 5) * 250, price: Math.round(Number(d.value) / 100), status: "Booked" } });

  // segments
  await db.insert(schema.segments).values([
    { workspaceId: ws, name: "Hot leads – Gulshan", definition: { match: "all", rules: [{ field: "project", op: "eq", value: "Gulshan Heights" }, { field: "deal_stage", op: "eq", value: "qualified" }] } },
    { workspaceId: ws, name: "Budget 2 Cr+", definition: { match: "any", rules: [{ field: "custom.budget", op: "eq", value: "2–3 Cr" }, { field: "custom.budget", op: "eq", value: "3 Cr +" }] }, audienceSync: { meta: true } },
    { workspaceId: ws, name: "Cold – no activity 14 days", definition: { match: "all", rules: [{ field: "last_activity_at", op: "lt", value: isoDay(-14) }, { field: "lifecycle_stage", op: "neq", value: "customer" }] } },
    { workspaceId: ws, name: "WhatsApp opted-in", definition: { match: "all", rules: [{ field: "consent:whatsapp", op: "eq", value: "opted_in" }] } },
  ]);
  const { refreshSegments } = await import("@/lib/services/segments");
  await refreshSegments(ctx);

  // journeys
  const welcome: schema.JourneyGraph = {
    nodes: [
      { id: "t", type: "trigger", position: { x: 260, y: 0 }, data: { label: "Contact created" } },
      { id: "a1", type: "action", position: { x: 260, y: 120 }, data: { label: "WhatsApp welcome", action: "send_message", channel: "whatsapp", body: "Hi {{first_name|there}}, thanks for your interest in {{project|ACE Developers}}! Your advisor {{owner_name|}} will call you shortly." } },
      { id: "a2", type: "action", position: { x: 260, y: 240 }, data: { label: "Alert owner", action: "notify_team", title: "New lead: {{name}} — call within 5 minutes" } },
      { id: "w1", type: "wait", position: { x: 260, y: 360 }, data: { label: "Wait 1 day", days: 1 } },
      { id: "c1", type: "condition", position: { x: 260, y: 480 }, data: { label: "Contacted?", match: "all", rules: [{ field: "deal_stage", op: "neq", value: "new" }] } },
      { id: "a3", type: "action", position: { x: 80, y: 620 }, data: { label: "Add tag nurtured", action: "add_tag", tag: "nurtured" } },
      { id: "a4", type: "action", position: { x: 440, y: 620 }, data: { label: "Escalation task", action: "create_task", title: "Lead still not contacted — call now", dueInHours: 1 } },
      { id: "g", type: "goal", position: { x: 260, y: 760 }, data: { label: "Done" } },
    ],
    edges: [
      { id: "e1", source: "t", target: "a1" }, { id: "e2", source: "a1", target: "a2" }, { id: "e3", source: "a2", target: "w1" }, { id: "e4", source: "w1", target: "c1" },
      { id: "e5", source: "c1", target: "a3", sourceHandle: "yes", label: "Yes" }, { id: "e6", source: "c1", target: "a4", sourceHandle: "no", label: "No" }, { id: "e7", source: "a3", target: "g" }, { id: "e8", source: "a4", target: "g" },
    ],
  };
  const [j1] = await db.insert(schema.journeys).values({ workspaceId: ws, name: "New lead welcome & SLA escalation", status: "live", version: 1, trigger: { type: "contact_created" }, graph: welcome, goal: { type: "stage_reached", value: "qualified" }, createdBy: adminId }).returning();
  await db.insert(schema.journeyVersions).values({ workspaceId: ws, journeyId: j1!.id, version: 1, trigger: j1!.trigger, graph: welcome, goal: j1!.goal });
  const visitGraph: schema.JourneyGraph = {
    nodes: [
      { id: "t", type: "trigger", position: { x: 200, y: 0 }, data: { label: "Stage → Site Visit" } },
      { id: "a1", type: "action", position: { x: 200, y: 120 }, data: { label: "Visit reminder (Bangla)", action: "send_message", channel: "whatsapp", body: "প্রিয় {{first_name|গ্রাহক}}, আপনার সাইট ভিজিট নিশ্চিত হয়েছে। ধন্যবাদ!" } },
      { id: "w", type: "wait", position: { x: 200, y: 240 }, data: { label: "Wait 2 days", days: 2 } },
      { id: "a2", type: "action", position: { x: 200, y: 360 }, data: { label: "Brochure email", action: "send_message", channel: "email", subject: "Your {{project}} brochure", body: "Dear {{first_name|there}}, thank you for visiting {{project}}. Here is the brochure: https://acedevelopers.com/brochure" } },
    ],
    edges: [{ id: "e1", source: "t", target: "a1" }, { id: "e2", source: "a1", target: "w" }, { id: "e3", source: "w", target: "a2" }],
  };
  await db.insert(schema.journeys).values({ workspaceId: ws, name: "Site visit nurture", status: "draft", version: 0, trigger: { type: "stage_changed", config: { stage: "site_visit" } }, graph: visitGraph, goal: { type: "stage_reached", value: "negotiation" }, createdBy: adminId });

  // forms & landing page
  const [form] = await db.insert(schema.forms).values({
    workspaceId: ws, type: "form", name: "Gulshan Heights enquiry", slug: "gulshan-heights-enquiry", status: "published", publishedVersion: 1,
    schema: { kind: "form", title: "Book a private viewing", description: "Luxury 3 & 4 bed apartments in Gulshan 2. Handover 2027.", submitLabel: "Request call-back", successMessage: "Thank you! Our advisor will call you within 5 minutes.", project: "Gulshan Heights", createDeal: true,
      fields: [{ key: "name", label: "Full name", type: "text", required: true }, { key: "phone", label: "Mobile number", type: "phone", required: true }, { key: "email", label: "Email", type: "email" }, { key: "budget", label: "Budget", type: "select", options: ["< 1 Cr", "1–2 Cr", "2–3 Cr", "3 Cr +"], mapTo: "custom.budget" }, { key: "timeline", label: "When are you planning to buy?", type: "select", options: ["Immediately", "Within 3 months", "3–6 months", "6–12 months"], mapTo: "custom.timeline" }],
      consent: [{ channel: "whatsapp", label: "Send me updates on WhatsApp" }, { channel: "email", label: "Email me the brochure and offers" }] },
    pixels: { metaPixelId: "880123456789", ga4Id: "G-ACEDEMO01" }, stats: { default: { views: 640, submits: 51 } },
  }).returning();
  await db.insert(schema.forms).values({
    workspaceId: ws, type: "page", name: "Gulshan Heights – launch page", slug: "gulshan-heights", status: "published", publishedVersion: 1,
    schema: { kind: "page", title: "Gulshan Heights", formId: form!.id, theme: { accent: "#2563EB" }, seo: { title: "Gulshan Heights by ACE Developers", description: "Luxury apartments in Gulshan 2" },
      blocks: [
        { id: "b1", type: "hero", props: { eyebrow: "ACE Developers presents", title: "Gulshan Heights", subtitle: "3 & 4 bedroom residences with lake views in Gulshan 2. Handover December 2027.", image: "https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?w=1400", cta: "Book a viewing" } },
        { id: "b2", type: "features", props: { title: "Why families choose Gulshan Heights", items: [{ title: "Prime location", text: "5 minutes to Gulshan Circle 2 and top schools." }, { title: "RAJUK approved", text: "All approvals in place, transparent paperwork." }, { title: "Flexible payment", text: "Easy instalments and bank loan support up to 70%." }] } },
        { id: "b3", type: "form", props: { title: "Request a call-back" } },
        { id: "b4", type: "faq", props: { title: "FAQ", items: [{ q: "When is handover?", a: "December 2027." }, { q: "Is parking included?", a: "Yes, one reserved car park per unit." }] } },
      ] },
    variants: [
      { key: "A", weight: 50, blocks: [] },
      { key: "B", weight: 50, blocks: [{ id: "b1", type: "hero", props: { eyebrow: "Limited launch offer", title: "Live above the lake in Gulshan 2", subtitle: "Book this month and save up to ৳10 lakh. Only 18 units left.", image: "https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?w=1400", cta: "Claim launch price" } }] },
    ],
    pixels: { metaPixelId: "880123456789" }, stats: { A: { views: 812, submits: 49 }, B: { views: 798, submits: 71 } },
  });

  // content calendar
  const day = (n: number, h = 11) => new Date(Date.now() + n * 86400000 + (h - new Date().getUTCHours()) * 3600000);
  await db.insert(schema.contentPosts).values([
    { workspaceId: ws, channels: ["facebook", "instagram"], campaign: "Gulshan Heights launch", body: "Lake-view living in Gulshan 2 🌿 3 & 4 bed residences, handover 2027. Book your private viewing today.", status: "published", scheduledAt: day(-6), publishedAt: day(-6), externalPostIds: { facebook: "sbx_fb_1", instagram: "sbx_ig_1" }, metrics: { reach: 18400, engagement: 1320, likes: 960, comments: 84, shares: 41 }, media: [{ url: "https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?w=800", type: "image" }] },
    { workspaceId: ws, channels: ["facebook"], campaign: "Bashundhara Residency", body: "বসুন্ধরায় আপনার স্বপ্নের ঠিকানা। সহজ কিস্তিতে বুকিং চলছে।", status: "scheduled", scheduledAt: day(2), approverId: users.marketing_manager },
    { workspaceId: ws, channels: ["instagram", "linkedin"], campaign: "NRB investors", body: "Investing back home? Meet our team at the Dubai property expo on Friday.", status: "in_review", scheduledAt: day(4), approvalToken: randomToken(18) },
    { workspaceId: ws, channels: ["facebook", "instagram"], campaign: "Gulshan Heights launch", body: "Behind the scenes: our site engineers on the 12th floor slab casting 🏗️", status: "draft", scheduledAt: day(7) },
    { workspaceId: ws, channels: ["tiktok"], campaign: "Lifestyle reels", body: "A day in the life at Uttara Greens – rooftop garden tour.", status: "approved", scheduledAt: day(9) },
  ]);

  await db.insert(schema.savedReports).values({ workspaceId: ws, name: "Weekly client report – ACE", config: { days: 7, sections: ["kpis", "funnel", "attribution", "campaigns", "reps"], whiteLabel: true }, schedule: "weekly_mon", recipients: ["client@acedevelopers.com"], shareToken: randomToken(18) });
  await db.insert(schema.aiAutoApproveRules).values({ workspaceId: ws, kind: "change_budget", maxBudgetChangePct: 0, active: false });

  // AI scoring (heuristic until enough history) + anomalies
  const { scoreLeads, detectAnomalies } = await import("@/lib/ai/features");
  await scoreLeads(ctx);
  await detectAnomalies(ctx).catch(() => {});

  // Module 11: social inbox demo (sandbox accounts, rules, knowledge base, saved replies)
  const { seedSocial } = await import("./seed-social");
  await seedSocial(ctx).catch((e) => console.error("[seed] social", e));

  // a second, isolated workspace (tenant isolation tests & agency sub-account demo)
  const au = await createWorkspace(db, workspace.agencyId, "Harbour Realty (AU demo)", "Australia/Sydney", "AUD", "en", "real_estate");
  await db.insert(schema.memberships).values({ workspaceId: au.id, userId: users.marketing_manager!, roleId: (await systemRole(db, "marketing_manager")).id });
  const auCtx: Ctx = { ...ctx, workspace: au };
  await captureLead({ ...auCtx, perms: { ...ctx.perms, contacts: "C" } }, { name: "Olivia Smith", phone: "0412 345 678", email: "olivia@example.com.au", attribution: { channel: "web_form", utmSource: "google" } });

  // historical conversions count as already synced (sandbox); clear queued side effects from seeding
  await db.update(schema.conversionSyncs).set({ status: "sent", sentAt: new Date(), response: { sandbox: true, seeded: true } }).where(eq(schema.conversionSyncs.status, "pending"));
  await db.delete(schema.jobs);
  await db.delete(schema.notifications).where(sql`${schema.notifications.createdAt} < now() - interval '1 second'`);
}
