/**
 * Module 11 acceptance tests (run: npm test). In-memory Postgres seeded with the demo workspace, whose social accounts
 * are sandbox integrations — every platform call goes through the connector layer in sandbox mode.
 */
process.env.PGLITE_DIR = "memory";
process.env.SEED_DEMO = "true";

import { test, before } from "node:test";
import assert from "node:assert/strict";
import { and, eq, sql } from "drizzle-orm";
import { getDb, schema, type DB } from "../src/db";
import type { Ctx } from "../src/lib/auth";
import { DEFAULT_ROLES } from "../src/lib/rbac";
import { classify, extractPhones } from "../src/lib/services/social-text";
import type { NormComment } from "../src/connectors/social";

let db: DB;
let ace: typeof schema.workspaces.$inferSelect;
let fb: typeof schema.socialAccounts.$inferSelect;
let ig: typeof schema.socialAccounts.$inferSelect;
let gbp: typeof schema.socialAccounts.$inferSelect;
const ctxFor = (roleKey = "workspace_admin", userId: string | null = null): Ctx => {
  const r = DEFAULT_ROLES.find((x) => x.key === roleKey)!;
  return { db, workspace: ace, user: userId ? { id: userId, name: "Test", email: "t@example.com", isAgencyAdmin: false, mfaEnabled: false, locale: null } : null, perms: r.permissions, roleKey, roleName: r.name, actor: { type: "user", id: userId, name: "Test" } };
};
let seq = 0;
const comment = (over: Partial<NormComment> = {}): NormComment => ({
  platform: "facebook", accountExternalId: fb.externalAccountId, commentId: `t_c_${++seq}_${Date.now()}`, authorId: `t_author_${seq}`, authorName: `Tester ${seq}`, body: "Hello", verb: "add",
  createdAt: new Date().toISOString(), object: { externalId: `t_post_${Math.floor(seq / 100)}`, type: "post", caption: "Test post" }, ...over,
});

before(async () => {
  db = await getDb();
  ace = (await db.select().from(schema.workspaces)).find((w) => w.name === "ACE Developers")!;
  const accts = await db.select().from(schema.socialAccounts).where(eq(schema.socialAccounts.workspaceId, ace.id));
  fb = accts.find((a) => a.platform === "facebook")!;
  ig = accts.find((a) => a.platform === "instagram")!;
  gbp = accts.find((a) => a.platform === "google_business")!;
  assert.ok(fb && ig && gbp, "sandbox social accounts seeded");
});

test("SOC-AI-001: rules-based classification handles English, Bangla and Banglish", () => {
  assert.equal(classify("Price koto? 3 bed er").intent, "price_inquiry");
  assert.equal(classify("দাম কত?").language, "bn");
  assert.equal(classify("dam koto bhai").language, "banglish");
  assert.equal(classify("This company is a fraud, worst service").sentiment, "negative");
  assert.ok(classify("Earn $500 daily with crypto, check my profile!!!").spam);
  assert.deepEqual(extractPhones("call 01719-556677 or ০১৮১৯৩৩৪৪৫৫"), ["+8801719556677", "+8801819334455"]);
});

test("SOC-001/004: accounts discovered, activated and 30-day backfill stored without firing rules", async () => {
  assert.equal(fb.status, "active");
  assert.equal(fb.backfill.status, "done");
  const threads = await db.select().from(schema.conversations).where(and(eq(schema.conversations.socialAccountId, fb.id), eq(schema.conversations.kind, "comment_thread")));
  assert.ok(threads.length >= 5, "backfilled comment threads");
  const reviews = await db.select().from(schema.reviews).where(eq(schema.reviews.socialAccountId, gbp.id));
  assert.ok(reviews.length >= 3, "backfilled reviews");
  const firings = await db.select().from(schema.ruleFirings).where(sql`${schema.ruleFirings.conversationId} IN (SELECT id FROM conversations WHERE social_account_id = ${fb.id} AND sla_due_at IS NULL AND first_response_at IS NULL)`);
  assert.equal(firings.length, 0, "historical items never trigger rules");
});

test("SOC-008: duplicate webhooks are ignored; edits keep history; removals mark deleted", async () => {
  const { ingestComment } = await import("../src/lib/services/social");
  const ctx = ctxFor();
  const c = comment({ body: "Is parking included?" });
  const first = await ingestComment(ctx, fb, c);
  assert.equal(first.status, "created");
  assert.equal((await ingestComment(ctx, fb, c)).status, "duplicate");
  await ingestComment(ctx, fb, { ...c, verb: "edited", body: "Is car parking included in the price?" });
  const row = await db.query.comments.findFirst({ where: eq(schema.comments.id, first.commentId!) });
  assert.equal(row!.body, "Is car parking included in the price?");
  assert.equal(row!.editHistory.length, 1);
  await ingestComment(ctx, fb, { ...c, verb: "remove" });
  assert.equal((await db.query.comments.findFirst({ where: eq(schema.comments.id, first.commentId!) }))!.isDeleted, true);
});

test("SOC-009/010: replies group into the parent thread; the page's own comments don't open conversations", async () => {
  const { ingestComment } = await import("../src/lib/services/social");
  const ctx = ctxFor();
  const parent = comment({ body: "When is handover?" });
  const p = await ingestComment(ctx, fb, parent);
  const child = await ingestComment(ctx, fb, comment({ body: "Also interested", parentId: parent.commentId, object: parent.object }));
  assert.equal(child.conversationId, p.conversationId);
  const own = await ingestComment(ctx, fb, comment({ authorId: fb.externalAccountId, body: "Thanks for following!" }));
  assert.equal(own.status, "own");
  assert.equal(own.conversationId, undefined);
});

test("SOC-050/§10: moderation runs before auto-reply — profanity is hidden and gets no public reply", async () => {
  const { ingestComment } = await import("../src/lib/services/social");
  const r = await ingestComment(ctxFor(), fb, comment({ body: "price koto? earn $500 daily with crypto check my profile" }));
  const c = await db.query.comments.findFirst({ where: eq(schema.comments.id, r.commentId!) });
  assert.equal(c!.isHidden, true);
  const replies = await db.select().from(schema.comments).where(and(eq(schema.comments.conversationId, r.conversationId!), eq(schema.comments.direction, "outbound")));
  assert.equal(replies.length, 0, "no reply after moderation stopped processing");
  const ev = await db.query.moderationEvents.findFirst({ where: eq(schema.moderationEvents.commentId, c!.id) });
  assert.equal(ev!.actorType, "rule");
});

test("SOC-042/040: phone in a public comment → hidden for privacy, attached to the contact, lead created, thanked publicly", async () => {
  const { ingestComment } = await import("../src/lib/services/social");
  const r = await ingestComment(ctxFor(), fb, comment({ body: "Please call me 01766-112233", authorName: "Phone Person" }));
  const c = await db.query.comments.findFirst({ where: eq(schema.comments.id, r.commentId!) });
  assert.equal(c!.isHidden, true);
  const contact = await db.query.contacts.findFirst({ where: eq(schema.contacts.id, c!.contactId!) });
  assert.ok(contact!.phones.includes("+8801766112233"));
  const consent = await db.select().from(schema.consents).where(eq(schema.consents.contactId, contact!.id));
  assert.ok(!consent.some((x) => x.status === "opted_in"), "sharing a number implies no marketing consent");
  const deal = await db.query.deals.findFirst({ where: eq(schema.deals.contactId, contact!.id) });
  assert.ok(deal, "lead/deal created");
  const replies = await db.select().from(schema.comments).where(and(eq(schema.comments.conversationId, r.conversationId!), eq(schema.comments.direction, "outbound")));
  assert.equal(replies.length, 1);
});

test("SOC-031/054: price comment → public reply + private reply, only once per person per post", async () => {
  const { ingestComment } = await import("../src/lib/services/social");
  const author = `t_price_${Date.now()}`;
  const obj = { externalId: `t_price_post_${Date.now()}`, type: "post", caption: "Gulshan Heights" };
  const r = await ingestComment(ctxFor(), fb, comment({ body: "dam koto?", authorId: author, authorName: "Price Asker", object: obj }));
  const out = await db.select().from(schema.comments).where(and(eq(schema.comments.conversationId, r.conversationId!), eq(schema.comments.direction, "outbound")));
  assert.equal(out.length, 1, "one public reply");
  assert.equal(out[0]!.sentByRuleId !== null, true);
  const pr = await db.query.events.findFirst({ where: and(eq(schema.events.name, "social.private_reply"), sql`${schema.events.properties}->>'comment_id' = ${r.commentId}`) });
  assert.ok(pr, "private reply sent");
  const dm = await db.query.conversations.findFirst({ where: eq(schema.conversations.id, String((pr!.properties as Record<string, unknown>).conversation_id)) });
  assert.equal(dm!.channel, "messenger");
  const again = await ingestComment(ctxFor(), fb, comment({ body: "price please?", authorId: author, authorName: "Price Asker", object: obj }));
  const out2 = await db.select().from(schema.comments).where(and(eq(schema.comments.conversationId, again.conversationId!), eq(schema.comments.direction, "outbound"), sql`${schema.comments.createdAt} > now() - interval '5 seconds'`));
  assert.equal(out2.filter((x) => x.sentByRuleId).length, 0, "rule did not fire twice for the same person on the same post");
});

test("SOC-031: a comment can receive only one private reply", async () => {
  const { ingestComment, privateReply } = await import("../src/lib/services/social");
  const ctx = ctxFor();
  const r = await ingestComment(ctx, fb, comment({ body: "Where is the site office?" }));
  await privateReply(ctx, r.commentId!, "Hi {{first_name}}, the site office is on Road 104.", { type: "user" });
  await assert.rejects(() => privateReply(ctx, r.commentId!, "Second", { type: "user" }), /already/i);
});

test("SOC-060/061: 1★ review is urgent and alerts; owner reply publishes and resolves", async () => {
  const { ingestReview, replyToReview } = await import("../src/lib/services/social");
  const ctx = ctxFor();
  const r = await ingestReview(ctx, gbp, { accountExternalId: gbp.externalAccountId, reviewId: `t_rev_${Date.now()}`, reviewerName: "Unhappy", rating: 1, body: "Terrible handover experience" });
  const conv = await db.query.conversations.findFirst({ where: eq(schema.conversations.id, r.conversationId!) });
  assert.equal(conv!.priority, "urgent");
  assert.ok(conv!.slaDueAt, "review SLA set");
  const rev = await db.query.reviews.findFirst({ where: eq(schema.reviews.conversationId, conv!.id) });
  await replyToReview(ctx, rev!.id, "We're sorry — our customer care lead will call you today.", { type: "user" });
  const after = await db.query.conversations.findFirst({ where: eq(schema.conversations.id, conv!.id) });
  assert.equal(after!.status, "resolved");
  assert.ok(after!.firstResponseAt);
  assert.equal((await db.query.reviews.findFirst({ where: eq(schema.reviews.id, rev!.id) }))!.replyStatus, "published");
});

test("SOC-071/028: SLA breaches are flagged; snoozed conversations wake up", async () => {
  const { ingestComment, socialMinute, setStatus } = await import("../src/lib/services/social");
  const ctx = ctxFor();
  const r = await ingestComment(ctx, ig, comment({ platform: "instagram", accountExternalId: ig.externalAccountId, body: "Is the rooftop shared?" }));
  await db.update(schema.conversations).set({ slaDueAt: new Date(Date.now() - 60000) }).where(eq(schema.conversations.id, r.conversationId!));
  const r2 = await ingestComment(ctx, ig, comment({ platform: "instagram", accountExternalId: ig.externalAccountId, body: "Any discount?" }));
  await setStatus(ctx, r2.conversationId!, "snoozed", new Date(Date.now() + 3600000));
  await db.update(schema.conversations).set({ snoozedUntil: new Date(Date.now() - 1000) }).where(eq(schema.conversations.id, r2.conversationId!));
  await socialMinute(ctx);
  assert.ok((await db.query.conversations.findFirst({ where: eq(schema.conversations.id, r.conversationId!) }))!.slaBreachedAt);
  assert.equal((await db.query.conversations.findFirst({ where: eq(schema.conversations.id, r2.conversationId!) }))!.status, "open");
});

test("SOC-026: collision lock — a second agent sees who is replying, and can take over", async () => {
  const { ingestComment, lockConversation } = await import("../src/lib/services/social");
  const users = await db.select({ id: schema.users.id }).from(schema.memberships).innerJoin(schema.users, eq(schema.users.id, schema.memberships.userId)).where(eq(schema.memberships.workspaceId, ace.id)).limit(2);
  const r = await ingestComment(ctxFor(), fb, comment({ body: "Is the gym included?" }));
  const a = await lockConversation(ctxFor("workspace_admin", users[0]!.id), r.conversationId!);
  assert.equal(a.locked, true);
  const b = await lockConversation(ctxFor("workspace_admin", users[1]!.id), r.conversationId!);
  assert.equal(b.locked, false);
  assert.ok(b.heldBy);
  const c = await lockConversation(ctxFor("workspace_admin", users[1]!.id), r.conversationId!, false, true);
  assert.equal(c.locked, true);
});

test("SOC-090/091: permissions — reps reply only to assigned threads, content can't manage rules, account restriction applies", async () => {
  const { ingestComment, replyToComment, assertSocial, allowedAccountIds } = await import("../src/lib/services/social");
  const rep = (await db.select({ userId: schema.memberships.userId, id: schema.memberships.id }).from(schema.memberships).innerJoin(schema.roles, eq(schema.roles.id, schema.memberships.roleId)).where(and(eq(schema.memberships.workspaceId, ace.id), eq(schema.roles.key, "sales_rep"))).limit(1))[0]!;
  const r = await ingestComment(ctxFor(), fb, comment({ body: "Is there a lift?" }));
  await db.update(schema.conversations).set({ assigneeId: null }).where(eq(schema.conversations.id, r.conversationId!));
  await assert.rejects(() => replyToComment(ctxFor("sales_rep", rep.userId), r.commentId!, "Yes", { type: "user", userId: rep.userId }), /assigned to someone else/);
  assert.throws(() => assertSocial(ctxFor("content"), "rules"), /rules/);
  assert.doesNotThrow(() => assertSocial(ctxFor("content"), "moderate"));
  await db.update(schema.memberships).set({ socialAccountIds: [ig.id] }).where(eq(schema.memberships.id, rep.id));
  assert.deepEqual(await allowedAccountIds(ctxFor("sales_rep", rep.userId)), [ig.id]);
  await db.update(schema.conversations).set({ assigneeId: rep.userId }).where(eq(schema.conversations.id, r.conversationId!));
  await assert.rejects(() => replyToComment(ctxFor("sales_rep", rep.userId), r.commentId!, "Yes", { type: "user", userId: rep.userId }), /social account/);
  await db.update(schema.memberships).set({ socialAccountIds: [] }).where(eq(schema.memberships.id, rep.id));
});

test("SOC-041/015: leads from ad comments are attributed to the comment channel, ad and campaign", async () => {
  const { ingestComment, createLeadFromConversation } = await import("../src/lib/services/social");
  const ad = await db.query.ads.findFirst({ where: eq(schema.ads.workspaceId, ace.id) });
  const r = await ingestComment(ctxFor(), fb, comment({ body: "Interested in this one", object: { externalId: `t_adpost_${Date.now()}`, type: "post", externalAdId: ad!.externalId! } }));
  const obj = await db.query.socialObjects.findFirst({ where: eq(schema.socialObjects.externalAdId, ad!.externalId!) });
  assert.equal(obj!.type, "ad");
  assert.ok(obj!.campaignName, "campaign resolved from the synced ad");
  const res = await createLeadFromConversation(ctxFor(), r.conversationId!, { type: "user" }, r.commentId);
  const deal = res.deal ?? (await db.query.deals.findFirst({ where: eq(schema.deals.contactId, res.contact.id) }));
  assert.ok(deal);
  const src = await db.query.leadSources.findFirst({ where: and(eq(schema.leadSources.contactId, res.contact.id), eq(schema.leadSources.channel, "facebook_comment")) });
  assert.ok(src, "lead source attributed to facebook_comment");
  assert.equal(src!.adId, ad!.externalId);
});

test("SOC-056: rule test mode classifies and lists actions without sending anything", async () => {
  const { testRules } = await import("../src/lib/services/social");
  const before = await db.select({ n: sql<number>`count(*)::int` }).from(schema.comments).where(eq(schema.comments.direction, "outbound"));
  const r = await testRules(ctxFor(), { text: "Price koto 3 bed?", trigger: "new_comment", channel: "facebook_comment", newContact: true });
  assert.equal(r.classification.intent, "price_inquiry");
  assert.ok(r.matched.some((m) => m.actions.some((a) => a.type === "public_reply")));
  const after = await db.select({ n: sql<number>`count(*)::int` }).from(schema.comments).where(eq(schema.comments.direction, "outbound"));
  assert.equal(after[0]!.n, before[0]!.n);
});

test("SOC-063: hides are logged and can be undone", async () => {
  const { ingestComment, moderateComment, undoModeration } = await import("../src/lib/services/social");
  const ctx = ctxFor();
  const r = await ingestComment(ctx, fb, comment({ body: "Not sure about this" }));
  await moderateComment(ctx, r.commentId!, "hide", { type: "user" }, "Off-topic");
  const ev = await db.query.moderationEvents.findFirst({ where: and(eq(schema.moderationEvents.commentId, r.commentId!), eq(schema.moderationEvents.action, "hide")) });
  await undoModeration(ctx, ev!.id);
  assert.equal((await db.query.comments.findFirst({ where: eq(schema.comments.id, r.commentId!) }))!.isHidden, false);
  assert.ok((await db.query.moderationEvents.findFirst({ where: eq(schema.moderationEvents.id, ev!.id) }))!.undoneAt);
});

test("SOC-002: Meta feed webhook payloads are normalised and ingested for the owning workspace", async () => {
  const { normalizeMeta } = await import("../src/connectors/social");
  const { handleMetaEvents, workspacesForMetaAccount } = await import("../src/lib/services/social-accounts");
  const cid = `wh_${Date.now()}`;
  const payload = { object: "page", entry: [{ id: fb.externalAccountId, changes: [{ field: "feed", value: { item: "comment", verb: "add", comment_id: cid, post_id: "wh_post_1", from: { id: "wh_user_1", name: "Webhook User" }, message: "Location kothay?", created_time: Math.floor(Date.now() / 1000) } }] }] };
  const events = normalizeMeta(payload);
  assert.equal(events.length, 1);
  assert.deepEqual(await workspacesForMetaAccount(fb.externalAccountId), [ace.id]);
  assert.equal(await handleMetaEvents(ctxFor(), events), 1);
  const row = await db.query.comments.findFirst({ where: eq(schema.comments.externalCommentId, cid) });
  assert.equal(row!.intent, "location_inquiry");
});

test("SOC-080/081: engagement report computes reply rate, first-response times and top posts", async () => {
  const { engagementReport } = await import("../src/lib/services/social");
  const r = await engagementReport(ctxFor(), new Date(Date.now() - 31 * 86400000), new Date(), "channel");
  assert.ok(r.total.conversations > 0);
  assert.ok(r.total.replied > 0);
  assert.ok(r.groups.some((g) => g.key === "facebook_comment"));
  assert.ok(r.topObjects.length > 0);
  assert.ok(r.rules.some((x) => x.totalFires > 0), "rule stats tracked");
});

test("Industry presets: neutral by default, real estate opt-in, booked step renamable", async () => {
  const { industryOf, INDUSTRIES } = await import("../src/lib/industry");
  assert.equal(industryOf(undefined).key, "general");
  assert.equal(industryOf({ industry: "real_estate" }).visit, "Site visit");
  assert.equal(industryOf({ industry: "healthcare" }).visit, "Appointment");
  assert.equal(industryOf({ industry: "services" }).key, "professional_services", "old keys still resolve");
  assert.equal(Object.values(INDUSTRIES).filter((p) => p.group !== "other").length, 17, "all 17 categories");
  assert.equal(industryOf({ industry: "automotive", visitLabel: "Showroom visit" }).visit, "Showroom visit");
  assert.equal(industryOf({ industry: "nope" }).key, "general");
  for (const p of Object.values(INDUSTRIES)) assert.ok(p.qualification.length >= 3, `${p.key} has qualification fields`);
});

test("Industry: a banking workspace gets a banking funnel, fields, AI questions, guardrails and starters", async () => {
  const { createWorkspace } = await import("../src/db/seed");
  const { funnel } = await import("../src/lib/services/analytics");
  const { nextBestAction } = await import("../src/lib/ai/features");
  const { captureLead } = await import("../src/lib/services/leads");
  const ws = await createWorkspace(db, ace.agencyId, `Bank ${Date.now()}`, "Asia/Dhaka", "BDT", "en", "financial_services");
  assert.equal(ws.settings?.industry, "financial_services");
  assert.equal(ws.settings?.social?.ai?.autopilot, false, "regulated: AI autopilot off");
  const pl = await db.query.pipelines.findFirst({ where: eq(schema.pipelines.workspaceId, ws.id) });
  assert.deepEqual(pl!.stages.map((s) => s.name), ["New", "Contacted", "Eligibility checked", "Branch appointment", "Application submitted", "KYC & documents", "Under review / approval", "Account opened / approved", "Lost"]);
  assert.equal(pl!.stages.find((s) => s.id === "site_visit")!.conversionEvent, "SiteVisit", "conversion mapping unchanged");
  assert.equal(pl!.stages.find((s) => s.id === "qualified")!.name, "Eligibility checked");
  const fields = await db.select().from(schema.customFieldDefs).where(eq(schema.customFieldDefs.workspaceId, ws.id));
  assert.ok(fields.some((f) => f.key === "kyc_status") && fields.some((f) => f.key === "product_interest"));
  const kb = await db.select().from(schema.knowledgeEntries).where(eq(schema.knowledgeEntries.workspaceId, ws.id));
  assert.ok(kb.length >= 3 && kb.every((k) => !k.isActive), "starter questions stay inactive until answered");
  const r = DEFAULT_ROLES.find((x) => x.key === "workspace_admin")!;
  const ctx: Ctx = { db, workspace: ws, user: null, perms: r.permissions, roleKey: r.key, roleName: r.name, actor: { type: "system", id: null, name: "Test" } };
  const f = await funnel(ctx, { from: new Date(Date.now() - 86400000), to: new Date() });
  assert.equal(f!.stages.find((s) => s.key === "visit")!.label, "Branch appointment");
  const lead = await captureLead(ctx, { name: "Loan Seeker", phone: "01733445566", attribution: { channel: "web_form" } });
  await db.update(schema.contacts).set({ firstContactedAt: new Date(Date.now() - 3 * 86400000), lastActivityAt: new Date() }).where(eq(schema.contacts.id, lead.contact.id));
  const nba = await nextBestAction(ctx, lead.contact.id);
  assert.match(nba.action, /product/i, "asks about the banking product, not budget/location/unit type");
  assert.doesNotMatch(nba.action, /unit|site visit/i);
});

test("Industry: switching an existing workspace with deals adds a new default pipeline and keeps old deals", async () => {
  const { createWorkspace } = await import("../src/db/seed");
  const { applyIndustry } = await import("../src/lib/services/industry");
  const { captureLead } = await import("../src/lib/services/leads");
  const ws = await createWorkspace(db, ace.agencyId, `Clinic ${Date.now()}`, "Asia/Dhaka", "BDT", "en", "general");
  const r = DEFAULT_ROLES.find((x) => x.key === "workspace_admin")!;
  const ctx: Ctx = { db, workspace: ws, user: null, perms: r.permissions, roleKey: r.key, roleName: r.name, actor: { type: "system", id: null, name: "Test" } };
  const lead = await captureLead(ctx, { name: "Patient One", phone: "01744556677", attribution: { channel: "web_form" } });
  const res = await applyIndustry(db, ws.id, "healthcare");
  assert.equal(res.pipeline, "added");
  const pls = await db.select().from(schema.pipelines).where(eq(schema.pipelines.workspaceId, ws.id));
  assert.equal(pls.length, 2);
  assert.equal(pls.find((p) => p.isDefault)!.stages.find((s) => s.id === "site_visit")!.name, "Appointment booked");
  const deal = await db.query.deals.findFirst({ where: eq(schema.deals.id, lead.deal!.id) });
  assert.equal(deal!.pipelineId, pls.find((p) => !p.isDefault)!.id, "existing deal untouched");
  assert.equal((await applyIndustry(db, ws.id, "healthcare")).savedReplies, 0, "re-applying adds nothing twice");
});
