/** Unified customer data — the spine (CDP-001…009). No module keeps a private copy of contact data. */
import { and, desc, eq, inArray, isNull, or, sql } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { audit } from "@/lib/audit";
import { emit } from "@/lib/webhooks";
import { ApiError } from "@/lib/api";
import { normalizeEmail, normalizePhone, fullName } from "@/lib/util";

export type Contact = typeof schema.contacts.$inferSelect;

export type ContactInput = {
  name?: string | null;
  firstName?: string | null;
  lastName?: string | null;
  email?: string | null;
  emails?: string[];
  phone?: string | null;
  phones?: string[];
  waId?: string | null;
  psid?: string | null;
  fbp?: string | null;
  deviceId?: string | null;
  anonymousId?: string | null;
  socialIds?: Record<string, string>;
  city?: string | null;
  territory?: string | null;
  project?: string | null;
  source?: string | null;
  ownerId?: string | null;
  lifecycleStage?: string;
  customFields?: Record<string, unknown>;
  tags?: string[];
};

function splitName(name?: string | null) {
  if (!name) return { first: null, last: null };
  const parts = name.trim().split(/\s+/);
  return { first: parts[0] ?? null, last: parts.slice(1).join(" ") || null };
}

export function identitiesFrom(input: ContactInput, defaultCountry = "880") {
  const out: { type: string; value: string }[] = [];
  for (const p of [input.phone, ...(input.phones ?? [])]) {
    const n = normalizePhone(p, defaultCountry);
    if (n) out.push({ type: "phone", value: n });
  }
  for (const e of [input.email, ...(input.emails ?? [])]) {
    const n = normalizeEmail(e);
    if (n) out.push({ type: "email", value: n });
  }
  if (input.waId) out.push({ type: "wa_id", value: input.waId.replace(/[^\d]/g, "") });
  if (input.psid) out.push({ type: "psid", value: input.psid });
  if (input.fbp) out.push({ type: "fbp", value: input.fbp });
  if (input.deviceId) out.push({ type: "device", value: input.deviceId });
  if (input.anonymousId) out.push({ type: "anonymous", value: input.anonymousId });
  const seen = new Set<string>();
  return out.filter((i) => (seen.has(i.type + i.value) ? false : (seen.add(i.type + i.value), true)));
}

const country = (ctx: Pick<Ctx, "workspace">) => ctx.workspace.settings?.defaultCountryCode ?? (ctx.workspace.currency === "AUD" ? "61" : ctx.workspace.currency === "USD" ? "1" : "880");

/**
 * CDP-002 identity resolution: create or update the single profile matching any normalised phone (E.164),
 * email or channel ID. When identifiers point at several existing contacts they are merged (logged & reversible).
 */
export async function upsertContact(ctx: Ctx, input: ContactInput, opts: { source?: string; skipJourneys?: boolean } = {}) {
  const ids = identitiesFrom(input, country(ctx));
  if (!ids.length && !input.name && !input.firstName) throw new ApiError(422, "validation_failed", "A contact needs at least a phone, email, channel ID or name");
  const ws = ctx.workspace.id;

  let matches: Contact[] = [];
  if (ids.length) {
    const found = await ctx.db.select({ contactId: schema.identities.contactId }).from(schema.identities).where(and(
      eq(schema.identities.workspaceId, ws),
      or(...ids.map((i) => and(eq(schema.identities.type, i.type), eq(schema.identities.valueNormalized, i.value)))),
    ));
    const cids = [...new Set(found.map((f) => f.contactId))];
    if (cids.length) matches = await ctx.db.select().from(schema.contacts).where(and(inArray(schema.contacts.id, cids), isNull(schema.contacts.deletedAt))).orderBy(schema.contacts.createdAt);
  }

  let contact: Contact;
  let created = false;
  const merged: string[] = [];
  const { first, last } = splitName(input.name);
  const firstName = input.firstName ?? first;
  const lastName = input.lastName ?? last;
  const phones = ids.filter((i) => i.type === "phone").map((i) => i.value);
  const emails = ids.filter((i) => i.type === "email").map((i) => i.value);

  if (!matches.length) {
    const [row] = await ctx.db.insert(schema.contacts).values({
      workspaceId: ws, firstName, lastName, phones, emails,
      socialIds: { ...(input.socialIds ?? {}), ...(input.waId ? { whatsapp: input.waId } : {}), ...(input.psid ? { messenger: input.psid } : {}) },
      ownerId: input.ownerId ?? null, lifecycleStage: input.lifecycleStage ?? "lead",
      city: input.city ?? null, territory: input.territory ?? input.city ?? null, project: input.project ?? null,
      source: input.source ?? opts.source ?? null, customFields: input.customFields ?? {}, tags: input.tags ?? [],
      createdBy: ctx.actor.type === "user" ? ctx.actor.id : null, lastActivityAt: new Date(),
    }).returning();
    contact = row!;
    created = true;
  } else {
    contact = matches[0]!;
    for (const other of matches.slice(1)) {
      await mergeContacts(ctx, contact.id, other.id, "auto: shared identifier");
      merged.push(other.id);
    }
    const fresh = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, contact.id) }))!;
    const before = { ...fresh };
    const patch: Partial<Contact> = {
      firstName: fresh.firstName || firstName, lastName: fresh.lastName || lastName,
      phones: [...new Set([...fresh.phones, ...phones])], emails: [...new Set([...fresh.emails, ...emails])],
      socialIds: { ...fresh.socialIds, ...(input.socialIds ?? {}), ...(input.waId ? { whatsapp: input.waId } : {}), ...(input.psid ? { messenger: input.psid } : {}) },
      city: fresh.city || input.city || null, territory: fresh.territory || input.territory || input.city || null, project: input.project || fresh.project,
      customFields: { ...fresh.customFields, ...(input.customFields ?? {}) }, tags: [...new Set([...fresh.tags, ...(input.tags ?? [])])],
      lastActivityAt: new Date(), updatedAt: new Date(),
    };
    if (input.ownerId) patch.ownerId = input.ownerId;
    const [row] = await ctx.db.update(schema.contacts).set(patch).where(eq(schema.contacts.id, fresh.id)).returning();
    contact = row!;
    const newTags = (input.tags ?? []).filter((t) => !before.tags.includes(t));
    if (!opts.skipJourneys) {
      const { triggerJourneys } = await import("./journeys");
      for (const t of newTags) await triggerJourneys(ctx, "tag_added", contact.id, { tag: t });
    }
  }

  if (ids.length) {
    await ctx.db.insert(schema.identities).values(ids.map((i) => ({ workspaceId: ws, contactId: contact.id, type: i.type, valueNormalized: i.value }))).onConflictDoNothing();
  }
  // CDP-003: anonymous visitors stitch to the contact on identification
  if (input.anonymousId) {
    await ctx.db.update(schema.events).set({ contactId: contact.id }).where(and(eq(schema.events.workspaceId, ws), eq(schema.events.anonymousId, input.anonymousId), isNull(schema.events.contactId)));
  }

  if (created) {
    await audit(ctx, "create", "contact", contact.id, undefined, contact);
    await emit(ctx.db, ws, "contact.created", { contact: publicContact(contact) });
    if (!opts.skipJourneys) {
      const { triggerJourneys } = await import("./journeys");
      await triggerJourneys(ctx, "contact_created", contact.id, {});
    }
  } else {
    await emit(ctx.db, ws, "contact.updated", { contact: publicContact(contact) });
  }
  return { contact, created, merged };
}

export function publicContact(c: Contact) {
  return {
    id: c.id, first_name: c.firstName, last_name: c.lastName, name: fullName(c), phones: c.phones, emails: c.emails, social_ids: c.socialIds,
    owner_id: c.ownerId, lifecycle_stage: c.lifecycleStage, score: c.score, city: c.city, territory: c.territory, project: c.project, source: c.source,
    custom_fields: c.customFields, tags: c.tags, created_at: c.createdAt, updated_at: c.updatedAt,
  };
}

const MOVABLE = [
  ["identities", schema.identities], ["events", schema.events], ["consents", schema.consents], ["leadSources", schema.leadSources],
  ["deals", schema.deals], ["activities", schema.activities], ["conversations", schema.conversations], ["journeyRuns", schema.journeyRuns],
  ["customObjectRecords", schema.customObjectRecords], ["submissions", schema.submissions],
] as const;

/** Merge `mergedId` into `survivorId`. All child rows move; the snapshot allows an exact undo (CDP-002). */
export async function mergeContacts(ctx: Ctx, survivorId: string, mergedId: string, reason = "manual") {
  if (survivorId === mergedId) throw new ApiError(400, "bad_request", "Cannot merge a contact into itself");
  const ws = ctx.workspace.id;
  const [a, b] = await Promise.all([
    ctx.db.query.contacts.findFirst({ where: and(eq(schema.contacts.id, survivorId), eq(schema.contacts.workspaceId, ws), isNull(schema.contacts.deletedAt)) }),
    ctx.db.query.contacts.findFirst({ where: and(eq(schema.contacts.id, mergedId), eq(schema.contacts.workspaceId, ws), isNull(schema.contacts.deletedAt)) }),
  ]);
  if (!a || !b) throw new ApiError(404, "not_found", "Contact not found");
  const moved: Record<string, string[]> = {};
  for (const [name, table] of MOVABLE) {
    const t = table as any;
    const rows = await ctx.db.update(t).set({ contactId: survivorId }).where(and(eq(t.workspaceId, ws), eq(t.contactId, mergedId))).returning({ id: t.id });
    moved[name] = (rows as { id: string }[]).map((r) => r.id);
  }
  const snapshot = { merged: b, survivorBefore: a, moved };
  await ctx.db.update(schema.contacts).set({
    phones: [...new Set([...a.phones, ...b.phones])], emails: [...new Set([...a.emails, ...b.emails])], tags: [...new Set([...a.tags, ...b.tags])],
    socialIds: { ...b.socialIds, ...a.socialIds }, customFields: { ...b.customFields, ...a.customFields },
    firstName: a.firstName || b.firstName, lastName: a.lastName || b.lastName, city: a.city || b.city, project: a.project || b.project,
    ownerId: a.ownerId || b.ownerId, score: Math.max(a.score ?? 0, b.score ?? 0) || null, updatedAt: new Date(),
  }).where(eq(schema.contacts.id, survivorId));
  await ctx.db.update(schema.contacts).set({ mergedIntoId: survivorId, deletedAt: new Date() }).where(eq(schema.contacts.id, mergedId));
  const [log] = await ctx.db.insert(schema.mergeLogs).values({ workspaceId: ws, survivorId, mergedId, reason, snapshot, createdBy: ctx.actor.type === "user" ? ctx.actor.id : null }).returning();
  await ctx.db.insert(schema.events).values({ workspaceId: ws, contactId: survivorId, name: "contact.merged", source: "system", properties: { merged_id: mergedId, merged_name: fullName(b), reason, merge_log_id: log!.id } });
  await audit(ctx, "merge", "contact", survivorId, { merged: mergedId }, { reason });
  await emit(ctx.db, ws, "contact.merged", { survivor_id: survivorId, merged_id: mergedId, reason });
  return log!;
}

export async function undoMerge(ctx: Ctx, mergeLogId: string) {
  const log = await ctx.db.query.mergeLogs.findFirst({ where: and(eq(schema.mergeLogs.id, mergeLogId), eq(schema.mergeLogs.workspaceId, ctx.workspace.id)) });
  if (!log) throw new ApiError(404, "not_found", "Merge not found");
  if (log.undoneAt) throw new ApiError(409, "conflict", "Merge already undone");
  const snap = log.snapshot as { merged: Contact; survivorBefore: Contact; moved: Record<string, string[]> };
  for (const [name, table] of MOVABLE) {
    const ids = snap.moved[name] ?? [];
    if (!ids.length) continue;
    const t = table as any;
    await ctx.db.update(t).set({ contactId: log.mergedId }).where(and(inArray(t.id, ids), eq(t.contactId, log.survivorId)));
  }
  const s = snap.survivorBefore;
  await ctx.db.update(schema.contacts).set({ phones: s.phones, emails: s.emails, tags: s.tags, socialIds: s.socialIds, customFields: s.customFields, firstName: s.firstName, lastName: s.lastName, updatedAt: new Date() }).where(eq(schema.contacts.id, log.survivorId));
  await ctx.db.update(schema.contacts).set({ mergedIntoId: null, deletedAt: null, updatedAt: new Date() }).where(eq(schema.contacts.id, log.mergedId));
  await ctx.db.update(schema.mergeLogs).set({ undoneAt: new Date() }).where(eq(schema.mergeLogs.id, log.id));
  await audit(ctx, "unmerge", "contact", log.survivorId, undefined, { restored: log.mergedId });
  return { restored: log.mergedId };
}

/* ---------------- Consent (CDP-004, NFR-010/011) ---------------- */

export const CHANNELS = ["email", "sms", "whatsapp", "messenger", "push"] as const;

export async function setConsent(ctx: Ctx, contactId: string, channel: string, status: "opted_in" | "opted_out", source: string) {
  await ctx.db.insert(schema.consents).values({ workspaceId: ctx.workspace.id, contactId, channel, status, source, createdBy: ctx.actor.type === "user" ? ctx.actor.id : null });
  await ctx.db.insert(schema.events).values({ workspaceId: ctx.workspace.id, contactId, name: `consent.${status}`, source, properties: { channel } });
  await audit(ctx, "consent", "contact", contactId, undefined, { channel, status, source });
}

export async function consentState(ctx: Pick<Ctx, "db" | "workspace">, contactId: string) {
  const rows = await ctx.db.select().from(schema.consents).where(and(eq(schema.consents.workspaceId, ctx.workspace.id), eq(schema.consents.contactId, contactId))).orderBy(desc(schema.consents.capturedAt));
  const state: Record<string, { status: string; source: string; at: Date }> = {};
  for (const r of rows) if (!state[r.channel]) state[r.channel] = { status: r.status, source: r.source, at: r.capturedAt };
  return { state, history: rows };
}

/** Opted-out contacts are excluded from all sends. US SMS requires explicit opt-in (TCPA). */
export async function canMessage(ctx: Pick<Ctx, "db" | "workspace">, contact: Contact, channel: string): Promise<{ ok: boolean; reason?: string }> {
  const { state } = await consentState(ctx, contact.id);
  const c = state[channel === "instagram" ? "messenger" : channel];
  if (c?.status === "opted_out") return { ok: false, reason: `Contact opted out of ${channel}` };
  if (channel === "sms" && contact.phones[0]?.startsWith("+1") && c?.status !== "opted_in") return { ok: false, reason: "US SMS requires explicit opt-in (TCPA)" };
  return { ok: true };
}

/* ---------------- Timeline ---------------- */

export type TimelineItem = { id: string; at: Date; kind: string; title: string; body?: string | null; meta?: Record<string, unknown> };

export async function timeline(ctx: Pick<Ctx, "db" | "workspace">, contactId: string, limit = 200): Promise<TimelineItem[]> {
  const ws = ctx.workspace.id;
  const [evs, acts, msgs, srcs] = await Promise.all([
    ctx.db.select().from(schema.events).where(and(eq(schema.events.workspaceId, ws), eq(schema.events.contactId, contactId))).orderBy(desc(schema.events.occurredAt)).limit(limit),
    ctx.db.select().from(schema.activities).where(and(eq(schema.activities.workspaceId, ws), eq(schema.activities.contactId, contactId))).orderBy(desc(schema.activities.createdAt)).limit(limit),
    ctx.db.select({ m: schema.messages }).from(schema.messages).innerJoin(schema.conversations, eq(schema.conversations.id, schema.messages.conversationId)).where(and(eq(schema.conversations.workspaceId, ws), eq(schema.conversations.contactId, contactId))).orderBy(desc(schema.messages.createdAt)).limit(limit),
    ctx.db.select().from(schema.leadSources).where(and(eq(schema.leadSources.workspaceId, ws), eq(schema.leadSources.contactId, contactId))),
  ]);
  const items: TimelineItem[] = [
    ...evs.filter((e) => e.name !== "lead.captured").map((e) => ({ id: e.id, at: e.occurredAt, kind: "event", title: eventTitle(e.name, e.properties), meta: { name: e.name, ...e.properties, source: e.source } })),
    ...acts.map((a) => ({ id: a.id, at: a.completedAt ?? a.createdAt, kind: a.type, title: a.title, body: a.body, meta: { outcome: a.outcome, dueAt: a.dueAt, recordingUrl: a.recordingUrl, completedAt: a.completedAt, duration: a.durationSec } })),
    ...msgs.map(({ m }) => ({ id: m.id, at: m.createdAt, kind: "message", title: `${m.direction === "in" ? "Received" : m.direction === "note" ? "Internal note" : m.status === "blocked" ? "Blocked" : m.status === "failed" ? "Failed to send" : "Sent"} ${m.channel}`, body: m.body, meta: { status: m.status, channel: m.channel, direction: m.direction } })),
    ...srcs.map((s) => ({ id: s.id, at: s.capturedAt, kind: "source", title: `Lead captured via ${s.channel.replace(/_/g, " ")}`, meta: { campaign: s.campaignId, adset: s.adsetId, ad: s.adId, utm_source: s.utmSource, utm_campaign: s.utmCampaign, fbclid: s.fbclid, gclid: s.gclid, landing: s.landingUrl } })),
  ];
  return items.sort((x, y) => y.at.getTime() - x.at.getTime()).slice(0, limit);
}

function eventTitle(name: string, p: Record<string, unknown>) {
  const map: Record<string, string> = {
    page_view: `Viewed ${p.path ?? p.url ?? "a page"}`, form_submit: `Submitted form ${p.form ?? ""}`, "deal.stage_changed": `Deal moved to ${p.to_name ?? p.to}`,
    "contact.merged": `Merged duplicate ${p.merged_name ?? ""}`, "consent.opted_in": `Opted in to ${p.channel}`, "consent.opted_out": `Opted out of ${p.channel}`,
    "conversion.sent": `Conversion ${p.event} sent to ${p.provider}`, "journey.entered": `Entered journey ${p.journey ?? ""}`, "journey.completed": `Completed journey ${p.journey ?? ""}`,
    "lead.assigned": `Assigned to ${p.owner_name ?? "rep"}`, "email.opened": "Opened email", "email.clicked": "Clicked email link", "sla.breached": "Response SLA breached",
  };
  return map[name] ?? name.replace(/[._]/g, " ");
}

/* ---------------- Export & deletion (CDP-009) ---------------- */

export async function exportContact(ctx: Ctx, contactId: string) {
  const c = await ctx.db.query.contacts.findFirst({ where: and(eq(schema.contacts.id, contactId), eq(schema.contacts.workspaceId, ctx.workspace.id)) });
  if (!c) throw new ApiError(404, "not_found", "Contact not found");
  const ws = ctx.workspace.id;
  const w = (t: any) => and(eq(t.workspaceId, ws), eq(t.contactId, contactId));
  const [identities, events, consents, sources, deals, activities, conversations, submissions] = await Promise.all([
    ctx.db.select().from(schema.identities).where(w(schema.identities)), ctx.db.select().from(schema.events).where(w(schema.events)),
    ctx.db.select().from(schema.consents).where(w(schema.consents)), ctx.db.select().from(schema.leadSources).where(w(schema.leadSources)),
    ctx.db.select().from(schema.deals).where(w(schema.deals)), ctx.db.select().from(schema.activities).where(w(schema.activities)),
    ctx.db.select().from(schema.conversations).where(w(schema.conversations)), ctx.db.select().from(schema.submissions).where(w(schema.submissions)),
  ]);
  const convIds = conversations.map((x) => x.id);
  const messages = convIds.length ? await ctx.db.select().from(schema.messages).where(inArray(schema.messages.conversationId, convIds)) : [];
  await audit(ctx, "export", "contact", contactId);
  return { exported_at: new Date().toISOString(), contact: publicContact(c), identities, events, consents, attribution: sources, deals, activities, conversations, messages, submissions };
}

/** Hard delete that propagates to every module (cascades) and queues provider-side removals. */
export async function deleteContact(ctx: Ctx, contactId: string) {
  const c = await ctx.db.query.contacts.findFirst({ where: and(eq(schema.contacts.id, contactId), eq(schema.contacts.workspaceId, ctx.workspace.id)) });
  if (!c) throw new ApiError(404, "not_found", "Contact not found");
  const ws = ctx.workspace.id;
  await ctx.db.delete(schema.events).where(and(eq(schema.events.workspaceId, ws), eq(schema.events.contactId, contactId)));
  await ctx.db.delete(schema.submissions).where(and(eq(schema.submissions.workspaceId, ws), eq(schema.submissions.contactId, contactId)));
  await ctx.db.delete(schema.conversionSyncs).where(and(eq(schema.conversionSyncs.workspaceId, ws), eq(schema.conversionSyncs.contactId, contactId)));
  await ctx.db.delete(schema.contacts).where(or(eq(schema.contacts.id, contactId), eq(schema.contacts.mergedIntoId, contactId)));
  await audit(ctx, "delete", "contact", contactId, { name: fullName(c) }, undefined);
  await emit(ctx.db, ws, "contact.deleted", { contact_id: contactId });
  const { enqueue } = await import("@/lib/jobs");
  await enqueue(ctx.db, "segments.refresh", { workspaceId: ws }, { workspaceId: ws });
  return { deleted: true };
}

export async function getContact(ctx: Pick<Ctx, "db" | "workspace">, id: string) {
  const c = await ctx.db.query.contacts.findFirst({ where: and(eq(schema.contacts.id, id), eq(schema.contacts.workspaceId, ctx.workspace.id)) });
  if (!c) throw new ApiError(404, "not_found", "Contact not found");
  if (c.mergedIntoId) {
    const s = await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, c.mergedIntoId) });
    if (s) return s;
  }
  return c;
}

export async function updateContact(ctx: Ctx, id: string, patch: Partial<Pick<Contact, "firstName" | "lastName" | "city" | "territory" | "project" | "ownerId" | "lifecycleStage" | "tags" | "customFields" | "phones" | "emails" | "score">>) {
  const before = await getContact(ctx, id);
  const next: Partial<Contact> = { ...patch, updatedAt: new Date() };
  if (patch.phones) next.phones = patch.phones.map((p) => normalizePhone(p, country(ctx))).filter(Boolean) as string[];
  if (patch.emails) next.emails = patch.emails.map(normalizeEmail).filter(Boolean) as string[];
  if (patch.customFields) next.customFields = { ...before.customFields, ...patch.customFields };
  const [after] = await ctx.db.update(schema.contacts).set(next).where(eq(schema.contacts.id, before.id)).returning();
  const ids = identitiesFrom({ phones: after!.phones, emails: after!.emails }, country(ctx));
  if (ids.length) await ctx.db.insert(schema.identities).values(ids.map((i) => ({ workspaceId: ctx.workspace.id, contactId: before.id, type: i.type, valueNormalized: i.value }))).onConflictDoNothing();
  await audit(ctx, "update", "contact", before.id, before, after);
  await emit(ctx.db, ctx.workspace.id, "contact.updated", { contact: publicContact(after!) });
  const { triggerJourneys } = await import("./journeys");
  for (const k of Object.keys(patch)) {
    if (k === "tags") for (const t of (patch.tags ?? []).filter((t) => !before.tags.includes(t))) await triggerJourneys(ctx, "tag_added", before.id, { tag: t });
    else if (k === "customFields") for (const f of Object.keys(patch.customFields ?? {})) if (before.customFields[f] !== patch.customFields![f]) await triggerJourneys(ctx, "field_changed", before.id, { field: f, value: patch.customFields![f] });
    else if (JSON.stringify((before as any)[k]) !== JSON.stringify((patch as any)[k])) await triggerJourneys(ctx, "field_changed", before.id, { field: k, value: (patch as any)[k] });
  }
  return after!;
}

export async function addTags(ctx: Ctx, id: string, tags: string[]) {
  const c = await getContact(ctx, id);
  return updateContact(ctx, id, { tags: [...new Set([...c.tags, ...tags])] });
}

export { sql };
