/**
 * Module 11 demo data: sandbox social accounts (Facebook, Instagram, YouTube, Google Business Profile), 30-day backfill,
 * engagement rules, knowledge base, saved replies and a few live comments that exercise the rules.
 * Idempotent: does nothing when the workspace already has social accounts.
 */
import { and, eq } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import type { RuleAction, RuleConditions, RuleSchedule } from "@/db/schema";

export async function seedSocial(ctx: Ctx) {
  const db = ctx.db;
  const ws = ctx.workspace.id;
  const existing = await db.query.socialAccounts.findFirst({ where: eq(schema.socialAccounts.workspaceId, ws) });
  if (existing) return { skipped: true };

  // settings: SLA targets, Bangladesh business week (Friday off), WhatsApp number for click-to-chat
  const social = { sla: { dm: 15, comment: 60, review: 1440 }, hours: { days: [0, 1, 2, 3, 4, 6], start: "09:00", end: "19:00" }, escalation: "notify" as const, featureFlags: { tiktok: false, linkedin: false }, ai: { autopilot: false, threshold: 0.85, publicReplies: true, languageMode: "match" as const, banglishReply: "banglish" as const, classify: true }, moderation: { blockedWords: [], competitorNames: [] }, whatsappNumber: "8801700000000", spikeThreshold: 20 };
  await db.update(schema.workspaces).set({ settings: { ...ctx.workspace.settings, social } }).where(eq(schema.workspaces.id, ws));
  const sctx: Ctx = { ...ctx, workspace: { ...ctx.workspace, settings: { ...ctx.workspace.settings, social } } };

  // sandbox integrations for YouTube and Google Business Profile (Meta already exists in the demo)
  const { writeSecret } = await import("@/lib/vault");
  for (const [provider, displayName] of [["youtube", "YouTube channel (sandbox)"], ["google_business", "Google Business Profile (sandbox)"]] as const) {
    const has = await db.query.integrations.findFirst({ where: and(eq(schema.integrations.workspaceId, ws), eq(schema.integrations.provider, provider)) });
    if (!has) await db.insert(schema.integrations).values({ workspaceId: ws, provider, displayName, accountRef: `${provider}-sandbox`, config: {}, tokenRef: await writeSecret(db, ws, { sandbox: "true" }), mode: "sandbox", status: "connected", lastSyncAt: new Date() });
  }
  const meta = await db.query.integrations.findFirst({ where: and(eq(schema.integrations.workspaceId, ws), eq(schema.integrations.provider, "meta")) });
  if (!meta) await db.insert(schema.integrations).values({ workspaceId: ws, provider: "meta", displayName: `${ctx.workspace.name} (sandbox)`, accountRef: "act_sandbox", config: {}, tokenRef: await writeSecret(db, ws, { sandbox: "true" }), mode: "sandbox", status: "connected" });

  const { discover, runBackfill } = await import("@/lib/services/social-accounts");
  const accounts = await discover(sctx);
  for (const a of accounts) {
    if (a.platform === "tiktok" || a.platform === "linkedin") continue; // behind feature flags until partner API approval
    await db.update(schema.socialAccounts).set({ status: "active", webhookSubscribed: ["facebook", "instagram"].includes(a.platform) }).where(eq(schema.socialAccounts.id, a.id));
    await runBackfill(sctx, a.id).catch((e) => console.error("[seed-social] backfill", a.name, e));
  }
  const fb = accounts.find((a) => a.platform === "facebook");
  const gbp = accounts.find((a) => a.platform === "google_business");

  // knowledge base (SOC-AI-003)
  await db.insert(schema.knowledgeEntries).values([
    { workspaceId: ws, question: "Gulshan Heights price for 3 bed / 4 bed apartments", answer: "3-bed (1,850 sqft) starts at BDT 2.4 crore; 4-bed (2,400 sqft) starts at BDT 3.2 crore. Share prices privately (inbox/WhatsApp), not in public comments.", scope: "Gulshan Heights", tags: ["price", "dam", "koto"], language: "en" },
    { workspaceId: ws, question: "Payment plan, booking money and installments", answer: "Booking money 10%, then 30% during construction in equal quarterly installments, balance on handover. Home loan support with partner banks.", scope: null, tags: ["payment", "installment", "kisti", "booking"], language: "en" },
    { workspaceId: ws, question: "Gulshan Heights location", answer: "Road 104, Gulshan 2, Dhaka — 3 minutes from Gulshan Lake Park. Google Maps pin: ACE Gulshan Heights.", scope: "Gulshan Heights", tags: ["location", "kothay", "address"], language: "en" },
    { workspaceId: ws, question: "Handover date", answer: "Gulshan Heights handover is planned for June 2027. Bashundhara Residency handover is planned for December 2026.", scope: null, tags: ["handover", "kobe"], language: "en" },
    { workspaceId: ws, question: "Site visit / showroom hours", answer: "Site visits Saturday–Thursday, 10am–6pm. Book a slot by replying with your preferred day or on WhatsApp.", scope: null, tags: ["visit", "showroom", "site"], language: "en" },
    { workspaceId: ws, question: "দাম কত? (Bashundhara Residency)", answer: "বসুন্ধরা রেসিডেন্সির ৩ বেডের ফ্ল্যাট ১.৬ কোটি টাকা থেকে শুরু। বিস্তারিত ইনবক্সে জানানো হবে।", scope: "Bashundhara Residency", tags: ["দাম", "price"], language: "bn" },
  ]);

  // saved replies (SOC-024)
  const saved: { shortcut: string; title: string; body: string; language: string; channels?: string[] }[] = [
    { shortcut: "/price", title: "Price → inbox", body: "Hi {{first_name}}! Thanks for your interest 😊 We've sent you the price list in your inbox.", language: "en" },
    { shortcut: "/dam", title: "দাম → ইনবক্স", body: "ধন্যবাদ {{first_name}}! দাম ও বিস্তারিত আপনার ইনবক্সে পাঠানো হয়েছে।", language: "bn" },
    { shortcut: "/location", title: "Location", body: "Gulshan Heights is on Road 104, Gulshan 2 — 3 minutes from Gulshan Lake Park. Would you like to book a site visit?", language: "en" },
    { shortcut: "/visit", title: "Book a visit", body: "We'd love to show you around, {{first_name}}! Site visits run Saturday–Thursday, 10am–6pm. Which day suits you?", language: "en" },
    { shortcut: "/sorry", title: "Complaint → private", body: "We're sorry to hear this, {{first_name}}. Please send us a message with your booking ID so our customer care team can resolve it today.", language: "en" },
    { shortcut: "/thanks", title: "Thanks for the review", body: "Thank you for the kind words, {{first_name}}! We're glad you're happy with your new home. 🏡", language: "en", channels: ["google_review", "facebook_comment", "instagram_comment"] },
  ];
  const { extractVariables } = await import("@/lib/util");
  await db.insert(schema.cannedReplies).values(saved.map((s) => ({ workspaceId: ws, ...s, channels: s.channels ?? [], variables: extractVariables(s.body) }))).onConflictDoNothing();

  // engagement rules (SOC-050…058) — moderation always evaluated first
  type R = { name: string; type: string; trigger: string; channels?: string[]; conditions: RuleConditions; actions: RuleAction[]; priority: number; stopProcessing?: boolean; schedule?: RuleSchedule; rateLimit?: Record<string, unknown> };
  const rules: R[] = [
    { name: "Hide profanity & spam", type: "moderation", trigger: "new_comment", conditions: { profanity: true }, actions: [{ type: "hide", config: { reason: "Profanity or spam" } }, { type: "tag", config: { tags: ["moderated"] } }], priority: 10, stopProcessing: true },
    { name: "Phone number in a public comment → hide for privacy, create lead", type: "moderation", trigger: "new_comment", conditions: { hasPhone: true }, actions: [{ type: "hide", config: { reason: "Personal phone number (privacy)" } }, { type: "create_lead" }, { type: "public_reply", config: { texts: ["Thanks {{first_name}}! We've hidden your number for your privacy — our team will call you shortly. 📞", "Got it {{first_name}} — number received and hidden for privacy. Expect a call from us soon!"] } }, { type: "tag", config: { tags: ["phone-shared"] } }], priority: 20, stopProcessing: true, rateLimit: { oncePerUserPerObject: true } },
    { name: "Price comments → public reply + brochure by private reply", type: "comment_to_dm", trigger: "new_comment", channels: ["facebook_comment", "instagram_comment"], conditions: { keywords: ["price", "dam", "koto", "দাম", "কত", "cost", "rate"], keywordMode: "any" }, actions: [{ type: "public_reply", config: { texts: ["Hi {{first_name}}! We've sent you the price details in your inbox 📩", "Thanks {{first_name}} — check your inbox for the full price list 😊", "ধন্যবাদ {{first_name}}! দাম ইনবক্সে পাঠানো হয়েছে 📩"] } }, { type: "private_reply", config: { texts: ["Hi {{first_name}}! Thanks for asking about {{project_name}}. 3-bed apartments start at BDT 2.4 crore and 4-bed at BDT 3.2 crore. Would you like the brochure on WhatsApp or a site visit this week?"] } }, { type: "tag", config: { tags: ["price-inquiry"] } }], priority: 50, rateLimit: { oncePerUserPerObject: true } },
    { name: "Price & booking questions → sales team, high priority", type: "routing", trigger: "any", conditions: { intents: ["price_inquiry", "booking", "interested"] }, actions: [{ type: "assign", config: { team: "sales" } }, { type: "set_priority", config: { priority: "high" } }], priority: 60 },
    { name: "After-hours away reply (DMs)", type: "auto_reply", trigger: "new_dm", conditions: {}, actions: [{ type: "public_reply", config: { texts: ["Thanks for your message! Our team is offline right now (Sat–Thu, 9am–7pm). We'll reply first thing tomorrow. For urgent help call 09612-000000."] } }], priority: 70, schedule: { mode: "out_of_hours" }, rateLimit: { oncePerUserPerDay: true } },
    { name: "Low-rating review → alert managers", type: "alert", trigger: "new_review", conditions: { maxRating: 2 }, actions: [{ type: "notify", config: { title: "Low Google review needs a reply" } }, { type: "set_priority", config: { priority: "urgent" } }], priority: 30 },
    { name: "Complaints → urgent, notify", type: "alert", trigger: "any", conditions: { intents: ["complaint", "legal"] }, actions: [{ type: "set_priority", config: { priority: "urgent" } }, { type: "notify" }, { type: "tag", config: { tags: ["complaint"] } }], priority: 40 },
  ];
  for (const r of rules) {
    await db.insert(schema.engagementRules).values({ workspaceId: ws, name: r.name, type: r.type, trigger: r.trigger, channels: r.channels ?? [], conditions: r.conditions, actions: r.actions, priority: r.priority, stopProcessing: !!r.stopProcessing, schedule: r.schedule ?? {}, rateLimit: r.rateLimit ?? {} });
  }

  // sales team for routing
  const members = await db.select({ id: schema.memberships.id, role: schema.roles.key }).from(schema.memberships).innerJoin(schema.roles, eq(schema.roles.id, schema.memberships.roleId)).where(eq(schema.memberships.workspaceId, ws));
  for (const m of members) if (m.role === "sales_rep") await db.update(schema.memberships).set({ team: "sales" }).where(eq(schema.memberships.id, m.id));

  // live items that run through the rules (ad comment with campaign context, price, phone, complaint, low review)
  const { simulateInbound } = await import("@/lib/services/social-accounts");
  const ad = await db.query.ads.findFirst({ where: eq(schema.ads.workspaceId, ws) });
  if (fb) {
    await simulateInbound(sctx, fb.id, { kind: "comment", text: "Dam koto 4 bed er? Gulshan e?", authorName: "Sadia Rahman", objectExternalId: "sbx_ad_post_1", objectCaption: "Gulshan Heights — lake-view 3 & 4 bed residences. Limited units.", externalAdId: ad?.externalId ?? undefined }).catch((e) => console.error("[seed-social]", e));
    await simulateInbound(sctx, fb.id, { kind: "comment", text: "Please call me, 01755-443322", authorName: "Kamal Uddin", objectExternalId: "sbx_ad_post_1", externalAdId: ad?.externalId ?? undefined }).catch((e) => console.error("[seed-social]", e));
    await simulateInbound(sctx, fb.id, { kind: "comment", text: "Your customer care never picks up. Worst experience, I want a refund of my booking money!", authorName: "Nadia Islam", objectExternalId: "sbx_post_2", objectCaption: "Behind the scenes at Bashundhara Residency 🏗️" }).catch((e) => console.error("[seed-social]", e));
    await simulateInbound(sctx, fb.id, { kind: "dm", text: "Hi, is there any 3 bed available in Bashundhara?", authorName: "Tahmid Hasan" }).catch((e) => console.error("[seed-social]", e));
  }
  if (gbp) await simulateInbound(sctx, gbp.id, { kind: "review", text: "Handover delayed by 8 months and nobody gives a clear answer.", authorName: "Ruhul Amin", rating: 1 }).catch((e) => console.error("[seed-social]", e));

  return { accounts: accounts.length, rules: rules.length };
}
