/**
 * Applies an industry preset to a workspace (lib/industry.ts). Non-destructive by design:
 * - pipeline: a pipeline without deals is re-staged in place; otherwise a new "<Industry> pipeline" is added and made default
 *   (existing deals keep their pipeline and stages)
 * - lead fields, starter knowledge-base questions (inactive until answered) and saved replies are only added when missing
 * - SLA and AI defaults follow the category (regulated categories keep AI autopilot and public price replies off)
 */
import { and, count, eq } from "drizzle-orm";
import { schema, type DB } from "@/db";
import { INDUSTRIES, industryStages, normalizeIndustry } from "@/lib/industry";
import { extractVariables } from "@/lib/util";

export async function applyIndustry(db: DB, workspaceId: string, industryKey: string, opts: { pipeline?: boolean; starters?: boolean } = {}) {
  const key = normalizeIndustry(industryKey);
  const p = INDUSTRIES[key]!;
  const ws = (await db.query.workspaces.findFirst({ where: eq(schema.workspaces.id, workspaceId) }))!;
  const social = ws.settings?.social ?? {};
  const settings = {
    ...ws.settings, industry: key,
    ...(p.regulated ? { social: { ...social, ai: { ...(social.ai ?? {}), autopilot: false, publicReplies: false } } } : {}),
  };
  await db.update(schema.workspaces).set({ settings, updatedAt: new Date() }).where(eq(schema.workspaces.id, workspaceId));
  const out = { industry: key, pipeline: "unchanged" as "unchanged" | "restaged" | "added", fields: 0, knowledge: 0, savedReplies: 0 };

  if (opts.pipeline !== false) {
    const stages = industryStages(key);
    const def = (await db.select().from(schema.pipelines).where(and(eq(schema.pipelines.workspaceId, workspaceId), eq(schema.pipelines.isDefault, true))).limit(1))[0];
    const [{ n }] = def ? await db.select({ n: count() }).from(schema.deals).where(eq(schema.deals.pipelineId, def.id)) : [{ n: 0 }];
    if (def && n === 0) {
      await db.update(schema.pipelines).set({ stages, slaMinutes: p.responseSlaMinutes, updatedAt: new Date() }).where(eq(schema.pipelines.id, def.id));
      out.pipeline = "restaged";
    } else if (def && JSON.stringify(def.stages.map((s) => s.name)) !== JSON.stringify(stages.map((s) => s.name))) {
      await db.update(schema.pipelines).set({ isDefault: false }).where(eq(schema.pipelines.workspaceId, workspaceId));
      await db.insert(schema.pipelines).values({ workspaceId, name: `${p.label} pipeline`, isDefault: true, stages, slaMinutes: p.responseSlaMinutes, slaAction: "alert" });
      out.pipeline = "added";
    } else if (!def) {
      await db.insert(schema.pipelines).values({ workspaceId, name: "Sales pipeline", isDefault: true, stages, slaMinutes: p.responseSlaMinutes, slaAction: "alert" });
      out.pipeline = "added";
    }
  }

  for (const f of p.fields) {
    const r = await db.insert(schema.customFieldDefs).values({ workspaceId, objectType: "contact", key: f.key, label: f.label, type: f.type, options: f.options ?? [] }).onConflictDoNothing().returning({ id: schema.customFieldDefs.id });
    out.fields += r.length;
  }

  if (opts.starters !== false) {
    const existingQ = new Set((await db.select({ q: schema.knowledgeEntries.question }).from(schema.knowledgeEntries).where(eq(schema.knowledgeEntries.workspaceId, workspaceId))).map((r) => r.q));
    for (const q of p.kbStarters) {
      if (existingQ.has(q)) continue;
      await db.insert(schema.knowledgeEntries).values({ workspaceId, question: q, answer: "(Add your answer — AI will not use this entry until it is answered and switched on.)", tags: ["starter", key], isActive: false });
      out.knowledge++;
    }
    const shortcuts = new Set((await db.select({ s: schema.cannedReplies.shortcut }).from(schema.cannedReplies).where(eq(schema.cannedReplies.workspaceId, workspaceId))).map((r) => r.s));
    for (const r of p.savedReplies) {
      if (shortcuts.has(r.shortcut)) continue;
      await db.insert(schema.cannedReplies).values({ workspaceId, shortcut: r.shortcut, title: r.title, body: r.body, variables: extractVariables(r.body), tags: [key] });
      out.savedReplies++;
    }
  }
  return out;
}
