/**
 * Requirement tests (run: npm test). Uses an in-memory Postgres (PGlite) seeded with the demo workspace.
 * Test names reference BRD requirement IDs, per the BRD's definition of done.
 */
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, can, allows } from "../src/lib/rbac";

let db: DB;
let ace: typeof schema.workspaces.$inferSelect;
let au: typeof schema.workspaces.$inferSelect;
const ctxFor = (workspace: typeof schema.workspaces.$inferSelect, roleKey = "workspace_admin", userId: string | null = null): Ctx => {
  const r = DEFAULT_ROLES.find((x) => x.key === roleKey)!;
  return { db, workspace, 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" } };
};

before(async () => {
  db = await getDb();
  const all = await db.select().from(schema.workspaces);
  ace = all.find((w) => w.name === "ACE Developers")!;
  au = all.find((w) => w.currency === "AUD")!;
  assert.ok(ace && au, "demo workspaces seeded");
});

test("CDP-002: phones in different formats merge into one contact (E.164)", async () => {
  const { upsertContact } = await import("../src/lib/services/contacts");
  const ctx = ctxFor(ace);
  const a = await upsertContact(ctx, { name: "Format Test", phone: "01811-223344" });
  const b = await upsertContact(ctx, { name: "Format Test", phone: "+880 1811 223344", email: "fmt@example.com" });
  assert.equal(a.contact.id, b.contact.id);
  assert.deepEqual(b.contact.phones, ["+8801811223344"]);
  assert.deepEqual(b.contact.emails, ["fmt@example.com"]);
});

test("CDP-002: shared identifiers merge two existing contacts, logged and reversible", async () => {
  const { upsertContact, undoMerge } = await import("../src/lib/services/contacts");
  const ctx = ctxFor(ace);
  const x = await upsertContact(ctx, { name: "Merge A", phone: "01911000001" });
  const y = await upsertContact(ctx, { name: "Merge B", email: "mergeb@example.com" });
  assert.notEqual(x.contact.id, y.contact.id);
  const z = await upsertContact(ctx, { phone: "01911000001", email: "mergeb@example.com" });
  assert.equal(z.merged.length, 1);
  const log = await db.query.mergeLogs.findFirst({ where: eq(schema.mergeLogs.survivorId, z.contact.id) });
  assert.ok(log, "merge logged");
  await undoMerge(ctx, log!.id);
  const restored = await db.query.contacts.findFirst({ where: eq(schema.contacts.id, log!.mergedId) });
  assert.equal(restored?.deletedAt, null);
});

test("CDP-004: opted-out contacts are excluded from sends", async () => {
  const { upsertContact, setConsent } = await import("../src/lib/services/contacts");
  const { sendMessage } = await import("../src/lib/services/messaging");
  const ctx = ctxFor(ace);
  const { contact } = await upsertContact(ctx, { name: "Opt Out", phone: "01711999888" });
  await setConsent(ctx, contact.id, "sms", "opted_out", "test");
  const r = await sendMessage(ctx, { contactId: contact.id, channel: "sms", body: "Hello", source: "human" });
  assert.equal(r.message?.status, "blocked");
});

test("MSG-007: template variables render from contact fields with fallbacks", async () => {
  const { renderTemplate } = await import("../src/lib/util");
  assert.equal(renderTemplate("Hi {{first_name|there}}, {{project|our project}}!", { first_name: "Rahim" }), "Hi Rahim, our project!");
  assert.equal(renderTemplate("{{custom.budget|n/a}}", { custom: { budget: "2 Cr" } }), "2 Cr");
});

test("MSG-001 / NFR-011: outside the 24h window WhatsApp requires an approved template", async () => {
  const { upsertContact } = await import("../src/lib/services/contacts");
  const { sendMessage } = await import("../src/lib/services/messaging");
  const ctx = ctxFor(ace);
  const { contact } = await upsertContact(ctx, { name: "WA Window", phone: "01611222333" });
  const free = await sendMessage(ctx, { contactId: contact.id, channel: "whatsapp", body: "free text", source: "human" });
  assert.equal(free.message?.status, "blocked");
  const tpl = await db.query.templates.findFirst({ where: and(eq(schema.templates.workspaceId, ace.id), eq(schema.templates.name, "welcome_enquiry")) });
  const ok = await sendMessage(ctx, { contactId: contact.id, channel: "whatsapp", templateId: tpl!.id, source: "human" });
  assert.equal(ok.message?.status, "sent");
});

test("FLOW-007: automated sends are deferred during quiet hours", async () => {
  const { quietHoursDelay } = await import("../src/lib/services/messaging");
  const ws = { ...ace, timezone: "UTC", settings: { quietHours: { enabled: true, start: "21:00", end: "09:00" } } };
  assert.ok(quietHoursDelay(ws as never, new Date("2026-11-03T23:30:00Z")));
  assert.equal(quietHoursDelay(ws as never, new Date("2026-11-03T12:00:00Z")), null);
});

test("LEAD-001/003: a captured lead creates contact + attribution + deal and is routed by project", async () => {
  const { captureLead } = await import("../src/lib/services/leads");
  const ctx = ctxFor(ace);
  const r = await captureLead(ctx, { name: "Routing Test", phone: "01511444555", project: "Gulshan Heights", attribution: { channel: "web_form", utmSource: "google", gclid: "abc" } });
  assert.ok(r.deal);
  const rafiq = await db.query.users.findFirst({ where: eq(schema.users.email, "rafiq@acedevelopers.com") });
  assert.equal(r.contact.ownerId, rafiq!.id);
  const src = await db.query.leadSources.findFirst({ where: eq(schema.leadSources.contactId, r.contact.id) });
  assert.equal(src?.gclid, "abc");
});

test("LEAD-007: Lost requires a reason and Won requires a value", async () => {
  const { captureLead, changeStage } = await import("../src/lib/services/leads");
  const ctx = ctxFor(ace);
  const r = await captureLead(ctx, { name: "Stage Rules", phone: "01311777888", attribution: { channel: "api" } });
  await assert.rejects(changeStage(ctx, r.deal!.id, "lost"), /reason/i);
  await assert.rejects(changeStage(ctx, r.deal!.id, "won"), /value/i);
  const won = await changeStage(ctx, r.deal!.id, "won", { value: 150000000 });
  assert.ok(won.wonAt);
});

test("LEAD-008 / ADS-003: stage changes queue conversion syncs to connected ad platforms", async () => {
  const { captureLead, changeStage } = await import("../src/lib/services/leads");
  const ctx = ctxFor(ace);
  const r = await captureLead(ctx, { name: "Conv Sync", phone: "01722111000", attribution: { channel: "meta_lead_ad", fbclid: "fb.x" } });
  await changeStage(ctx, r.deal!.id, "qualified");
  const rows = await db.select().from(schema.conversionSyncs).where(and(eq(schema.conversionSyncs.dealId, r.deal!.id), eq(schema.conversionSyncs.eventName, "Qualified")));
  assert.deepEqual(rows.map((x) => x.provider).sort(), ["google", "meta"]);
});

test("ADS-003: conversion send marks the sync as sent (sandbox) with hashed identifiers", async () => {
  const { sendConversion } = await import("../src/lib/services/conversions");
  const ctx = ctxFor(ace);
  const pending = await db.query.conversionSyncs.findFirst({ where: and(eq(schema.conversionSyncs.workspaceId, ace.id), eq(schema.conversionSyncs.status, "pending"), eq(schema.conversionSyncs.provider, "meta")) });
  assert.ok(pending);
  const integ = await db.query.integrations.findFirst({ where: and(eq(schema.integrations.workspaceId, ace.id), eq(schema.integrations.provider, "meta")) });
  await sendConversion(ctx, pending!.id, integ!.id);
  const after = await db.query.conversionSyncs.findFirst({ where: eq(schema.conversionSyncs.id, pending!.id) });
  assert.equal(after?.status, "sent");
  const ud = (after?.payload as any)?.userData;
  assert.match(ud.ph[0], /^[a-f0-9]{64}$/);
});

test("NFR-001: data never leaks between workspaces", async () => {
  const { getContact } = await import("../src/lib/services/contacts");
  const auContact = await db.query.contacts.findFirst({ where: eq(schema.contacts.workspaceId, au.id) });
  await assert.rejects(getContact(ctxFor(ace), auContact!.id), /not found/i);
  const { countSegment } = await import("../src/lib/services/segments");
  const all = await countSegment(ctxFor(au), { match: "all", rules: [] });
  const [{ n }] = (await db.select({ n: sql<number>`count(*)::int` }).from(schema.contacts).where(and(eq(schema.contacts.workspaceId, au.id), sql`deleted_at IS NULL`))) as [{ n: number }];
  assert.equal(all, n);
});

test("AUTH-001 / ADM-007: permission matrix and API key scopes", async () => {
  const rep = DEFAULT_ROLES.find((r) => r.key === "sales_rep")!.permissions;
  const viewer = DEFAULT_ROLES.find((r) => r.key === "client_viewer")!.permissions;
  assert.equal(can(rep, "contacts", "edit"), true);
  assert.equal(can(rep, "ads", "view"), false);
  assert.equal(can(viewer, "content", "approve"), true);
  assert.equal(can(viewer, "contacts", "edit"), false);
  assert.equal(allows("V", "edit"), false);
  const { requireScope } = await import("../src/lib/api");
  const keyCtx = { ...ctxFor(ace), scopes: ["read:contacts"] };
  assert.doesNotThrow(() => requireScope(keyCtx, "read:contacts"));
  assert.throws(() => requireScope(keyCtx, "write:contacts"), /scope/);
});

test("CDP-006: segment rules compile to SQL and count members", async () => {
  const { countSegment } = await import("../src/lib/services/segments");
  const ctx = ctxFor(ace);
  const gulshan = await countSegment(ctx, { match: "all", rules: [{ field: "project", op: "eq", value: "Gulshan Heights" }] });
  const any = await countSegment(ctx, { match: "any", rules: [{ field: "project", op: "eq", value: "Gulshan Heights" }, { field: "project", op: "eq", value: "Uttara Greens" }] });
  assert.ok(gulshan > 0 && any > gulshan);
});

test("FLOW-001/004: journeys enrol on trigger, pin to their version and log steps", async () => {
  const { publishJourney, triggerJourneys, advanceRun } = await import("../src/lib/services/journeys");
  const ctx = ctxFor(ace);
  const [j] = await db.insert(schema.journeys).values({ workspaceId: ace.id, name: "Test journey", status: "draft", trigger: { type: "tag_added", config: { tag: "test-journey" } }, graph: { nodes: [{ id: "t", type: "trigger", position: { x: 0, y: 0 }, data: {} }, { id: "a", type: "action", position: { x: 0, y: 100 }, data: { action: "add_tag", tag: "journeyed" } }], edges: [{ id: "e", source: "t", target: "a" }] } }).returning();
  await publishJourney(ctx, j!.id);
  const { upsertContact } = await import("../src/lib/services/contacts");
  const { contact } = await upsertContact(ctx, { name: "Journey Person", phone: "01999123123" });
  await triggerJourneys(ctx, "tag_added", contact.id, { tag: "test-journey" });
  const run = await db.query.journeyRuns.findFirst({ where: and(eq(schema.journeyRuns.journeyId, j!.id), eq(schema.journeyRuns.contactId, contact.id)) });
  assert.equal(run?.version, 1);
  await advanceRun(run!.id);
  const done = await db.query.journeyRuns.findFirst({ where: eq(schema.journeyRuns.id, run!.id) });
  assert.equal(done?.status, "completed");
  const c = await db.query.contacts.findFirst({ where: eq(schema.contacts.id, contact.id) });
  assert.ok(c?.tags.includes("journeyed"));
});

test("ANL-003: multi-touch weights sum to 1", async () => {
  const { weightsFor } = await import("../src/lib/services/analytics");
  const times = [new Date("2026-10-01"), new Date("2026-10-10"), new Date("2026-10-20")];
  for (const m of ["first_touch", "last_touch", "linear", "time_decay", "position_based"]) {
    const w = weightsFor(m, times, new Date("2026-10-25"));
    assert.ok(Math.abs(w.reduce((a, b) => a + b, 0) - 1) < 1e-9, m);
  }
  assert.deepEqual(weightsFor("position_based", times, new Date()), [0.4, 0.2, 0.4]);
});

test("PAGE-002: invalid phone numbers are rejected", async () => {
  const { isValidPhone } = await import("../src/lib/util");
  assert.equal(isValidPhone("01712345678"), true);
  assert.equal(isValidPhone("0171234"), false);
  assert.equal(isValidPhone("01012345678"), false);
  assert.equal(isValidPhone("0412 345 678", "61"), true);
});

test("INT-004: outbound webhook signatures are HMAC-SHA256", async () => {
  const { hmac } = await import("../src/lib/crypto");
  // RFC 4231-style known vector
  assert.equal(hmac("key", "The quick brown fox jumps over the lazy dog"), "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8");
});

test("NFR-002: vault encrypts secrets with AES-256-GCM", async () => {
  const { encrypt, decrypt } = await import("../src/lib/crypto");
  const c = encrypt("token-123");
  assert.notEqual(c, "token-123");
  assert.equal(decrypt(c), "token-123");
});

test("ADM-002: TOTP codes verify within the time window", async () => {
  const { newTotpSecret, totp, verifyTotp } = await import("../src/lib/crypto");
  const s = newTotpSecret();
  assert.equal(verifyTotp(s, totp(s)), true);
  assert.equal(verifyTotp(s, "000000") && totp(s) !== "000000", false);
});

test("AI-008: spend actions wait for approval; reps cannot approve", async () => {
  const { proposeAction, decideAction } = await import("../src/lib/ai/features");
  const ctx = ctxFor(ace, "performance");
  const camp = await db.query.campaigns.findFirst({ where: eq(schema.campaigns.workspaceId, ace.id) });
  const a = await proposeAction(ctx, { agent: "test", kind: "change_budget", proposedAction: { campaignId: camp!.id, changePct: 10 }, reasoning: "test", expectedImpact: "test" });
  assert.equal(a.status, "proposed");
  await assert.rejects(decideAction(ctxFor(ace, "performance"), a.id, "approve"), /approve/i);
  const done = await decideAction(ctxFor(ace, "marketing_manager"), a.id, "approve");
  assert.equal(done.status, "executed");
  const log = await db.query.auditLogs.findFirst({ where: and(eq(schema.auditLogs.objectId, camp!.id), eq(schema.auditLogs.action, "ads.change_budget")) });
  assert.ok(log?.before && log?.after, "write logged with before/after");
});

test("AI-005: ask-your-data falls back to rule-based planning without an API key", async () => {
  const { ruleBasedPlan } = await import("../src/lib/ai/features");
  const p = ruleBasedPlan("Which ad set brought the most site visits last month?");
  assert.equal(p.metric, "site_visits");
  assert.equal(p.dimension, "adset");
});

test("ADM-004: invoice lines include plan and overage", async () => {
  const { buildInvoiceLines } = await import("../src/lib/services/billing");
  const r = buildInvoiceLines("starter", "BDT", { sms: 600, whatsapp: 0, email: 0, ai_credits: 0, contacts: 100, seats: 2 });
  assert.equal(r.lines.length, 2);
  assert.equal(r.lines[1]!.quantity, 100);
});
