/** Lead management (LEAD-001…008): capture, routing, pipeline, tasks, activity logging. */
import { and, asc, desc, eq, inArray, isNull, sql } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { activeUsers } from "@/lib/auth";
import { audit } from "@/lib/audit";
import { emit } from "@/lib/webhooks";
import { enqueue } from "@/lib/jobs";
import { ApiError } from "@/lib/api";
import { fullName } from "@/lib/util";
import { upsertContact, setConsent, type ContactInput } from "./contacts";
import { notifyUser, notifyAdmins } from "./notify";

export type Attribution = {
  channel: string; campaignId?: string; adsetId?: string; adId?: string;
  utmSource?: string; utmMedium?: string; utmCampaign?: string; utmTerm?: string; utmContent?: string;
  fbclid?: string; gclid?: string; landingUrl?: string; formId?: string;
};

export type LeadInput = ContactInput & {
  attribution: Attribution;
  externalId?: string;
  dealTitle?: string;
  value?: number;
  pipelineId?: string;
  createDeal?: boolean;
  consents?: { channel: string; status: "opted_in" | "opted_out" }[];
  note?: string;
  /** attach to an existing contact instead of resolving by identifiers (e.g. a social commenter) */
  contactId?: string;
};

export async function defaultPipeline(ctx: Pick<Ctx, "db" | "workspace">) {
  const ps = await ctx.db.select().from(schema.pipelines).where(eq(schema.pipelines.workspaceId, ctx.workspace.id)).orderBy(desc(schema.pipelines.isDefault), asc(schema.pipelines.createdAt));
  if (!ps[0]) throw new ApiError(409, "conflict", "No pipeline configured for this workspace");
  return ps[0];
}

/** LEAD-001 / POST /v1/leads: creates or updates contact + attribution + deal in one call. */
export async function captureLead(ctx: Ctx, input: LeadInput) {
  const ws = ctx.workspace.id;
  if (input.externalId) {
    const dup = await ctx.db.select({ id: schema.events.id, contactId: schema.events.contactId }).from(schema.events)
      .where(and(eq(schema.events.workspaceId, ws), eq(schema.events.name, "lead.captured"), sql`${schema.events.properties}->>'external_id' = ${input.externalId}`)).limit(1);
    if (dup[0]?.contactId) {
      const c = await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, dup[0].contactId) });
      return { contact: c!, deal: null, duplicate: true, created: false };
    }
  }
  let contact: Awaited<ReturnType<typeof upsertContact>>["contact"];
  let created = false;
  if (input.contactId) {
    const existing = await ctx.db.query.contacts.findFirst({ where: and(eq(schema.contacts.id, input.contactId), eq(schema.contacts.workspaceId, ws)) });
    if (!existing) throw new ApiError(404, "not_found", "Contact not found");
    contact = existing;
    if (["social_engager", "subscriber"].includes(existing.lifecycleStage)) [contact] = await ctx.db.update(schema.contacts).set({ lifecycleStage: "lead", project: input.project ?? existing.project, source: existing.source ?? input.attribution.channel, updatedAt: new Date() }).where(eq(schema.contacts.id, existing.id)).returning() as [typeof existing];
  } else ({ contact, created } = await upsertContact(ctx, { ...input, source: input.source ?? input.attribution.channel }, { source: input.attribution.channel }));
  const a = input.attribution;
  const pipeline = input.pipelineId ? await ctx.db.query.pipelines.findFirst({ where: and(eq(schema.pipelines.id, input.pipelineId), eq(schema.pipelines.workspaceId, ws)) }) : await defaultPipeline(ctx);
  if (!pipeline) throw new ApiError(404, "not_found", "Pipeline not found");

  let deal = (await ctx.db.select().from(schema.deals).where(and(eq(schema.deals.workspaceId, ws), eq(schema.deals.contactId, contact.id), eq(schema.deals.pipelineId, pipeline.id), isNull(schema.deals.wonAt), isNull(schema.deals.lostAt))).limit(1))[0] ?? null;
  let dealCreated = false;
  if (!deal && input.createDeal !== false) {
    const first = [...pipeline.stages].sort((x, y) => x.order - y.order)[0]!;
    [deal] = await ctx.db.insert(schema.deals).values({
      workspaceId: ws, contactId: contact.id, pipelineId: pipeline.id, stageId: first.id,
      title: input.dealTitle ?? `${fullName(contact)}${input.project ? ` · ${input.project}` : ""}`,
      value: input.value ?? 0, currency: ctx.workspace.currency, project: input.project ?? contact.project,
      slaDueAt: new Date(Date.now() + pipeline.slaMinutes * 60000), position: Date.now(),
    }).returning();
    dealCreated = true;
  }
  await ctx.db.insert(schema.leadSources).values({
    workspaceId: ws, contactId: contact.id, dealId: deal?.id ?? null, channel: a.channel, campaignId: a.campaignId, adsetId: a.adsetId, adId: a.adId,
    utmSource: a.utmSource, utmMedium: a.utmMedium, utmCampaign: a.utmCampaign, utmTerm: a.utmTerm, utmContent: a.utmContent,
    fbclid: a.fbclid, gclid: a.gclid, landingUrl: a.landingUrl, formId: a.formId ?? null,
  });
  for (const c of input.consents ?? []) await setConsent(ctx, contact.id, c.channel, c.status, a.channel);
  if (input.note) await ctx.db.insert(schema.activities).values({ workspaceId: ws, contactId: contact.id, dealId: deal?.id, type: "note", title: "Lead note", body: input.note });

  await ctx.db.insert(schema.events).values({ workspaceId: ws, contactId: contact.id, name: "lead.captured", source: a.channel, properties: { external_id: input.externalId ?? null, channel: a.channel, campaign_id: a.campaignId ?? null, ad_id: a.adId ?? null, deal_id: deal?.id ?? null } });

  // LEAD-003: assign + notify within 30s
  let ownerId = contact.ownerId;
  if (!ownerId) ownerId = await routeLead(ctx, contact.id, { source: a.channel, project: input.project ?? contact.project, territory: contact.territory ?? contact.city });
  if (deal && !deal.ownerId && ownerId) {
    [deal] = await ctx.db.update(schema.deals).set({ ownerId }).where(eq(schema.deals.id, deal.id)).returning();
  }
  if (ownerId) await notifyUser(ctx, ownerId, "lead", `New lead: ${fullName(contact)}`, `${a.channel.replace(/_/g, " ")}${input.project ? ` · ${input.project}` : ""}${contact.phones[0] ? ` · ${contact.phones[0]}` : ""}`, `/contacts/${contact.id}`);

  await emit(ctx.db, ws, "lead.captured", { contact_id: contact.id, deal_id: deal?.id ?? null, channel: a.channel, attribution: a, created });
  if (deal && dealCreated) {
    const { queueConversions } = await import("./conversions");
    await queueConversions(ctx, { dealId: deal.id, contactId: contact.id, eventName: "Lead", value: 0 });
  }
  await audit(ctx, "lead.capture", "contact", contact.id, undefined, { channel: a.channel, deal: deal?.id });
  const fresh = await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, contact.id) });
  return { contact: fresh!, deal, duplicate: false, created };
}

/** LEAD-003 routing: round-robin, by source, by project, by territory, by workload. */
export async function routeLead(ctx: Ctx, contactId: string, attrs: { source?: string | null; project?: string | null; territory?: string | null }) {
  const ws = ctx.workspace.id;
  const rules = await ctx.db.select().from(schema.routingRules).where(and(eq(schema.routingRules.workspaceId, ws), eq(schema.routingRules.active, true))).orderBy(asc(schema.routingRules.priority));
  const members = await activeUsers(ctx.db, ws);
  const memberIds = new Set(members.map((m) => m.id));
  const eqi = (x?: string | null, y?: string | null) => !!x && !!y && x.trim().toLowerCase() === y.trim().toLowerCase();

  let rule = rules.find((r) => {
    const m = r.match ?? {};
    if (m.source && !eqi(m.source, attrs.source)) return false;
    if (m.project && !eqi(m.project, attrs.project)) return false;
    if (m.territory && !eqi(m.territory, attrs.territory)) return false;
    return true;
  });
  let pool: string[] = rule ? rule.userIds.filter((u) => memberIds.has(u)) : [];
  if (!rule || !pool.length) {
    const reps = await ctx.db.select({ userId: schema.memberships.userId }).from(schema.memberships).innerJoin(schema.roles, eq(schema.roles.id, schema.memberships.roleId))
      .where(and(eq(schema.memberships.workspaceId, ws), eq(schema.memberships.active, true), eq(schema.roles.key, "sales_rep")));
    pool = reps.map((r) => r.userId).filter((u) => memberIds.has(u));
    // territory/project fallbacks based on membership attributes
    if (rule?.strategy === "territory" || (!rule && attrs.territory)) {
      const t = members.filter((m) => pool.includes(m.id) && eqi(m.territory, attrs.territory)).map((m) => m.id);
      if (t.length) pool = t;
    }
    if (attrs.project) {
      const p = members.filter((m) => pool.includes(m.id) && m.projects.some((x) => eqi(x, attrs.project))).map((m) => m.id);
      if (p.length) pool = p;
    }
    rule = rule && rule.userIds.length ? rule : undefined;
  }
  if (!pool.length) return null;

  let chosen: string;
  if (rule?.strategy === "workload") {
    const loads = await ctx.db.select({ ownerId: schema.deals.ownerId, n: sql<number>`count(*)::int` }).from(schema.deals)
      .where(and(eq(schema.deals.workspaceId, ws), inArray(schema.deals.ownerId, pool), isNull(schema.deals.wonAt), isNull(schema.deals.lostAt))).groupBy(schema.deals.ownerId);
    const map = new Map(loads.map((l) => [l.ownerId, l.n]));
    chosen = [...pool].sort((x, y) => (map.get(x) ?? 0) - (map.get(y) ?? 0))[0]!;
  } else if (rule) {
    chosen = pool[rule.cursor % pool.length]!;
    await ctx.db.update(schema.routingRules).set({ cursor: rule.cursor + 1 }).where(eq(schema.routingRules.id, rule.id));
  } else {
    // global round-robin: least recently assigned rep
    const last = await ctx.db.select({ ownerId: schema.contacts.ownerId, at: sql<Date>`max(${schema.contacts.updatedAt})` }).from(schema.contacts)
      .where(and(eq(schema.contacts.workspaceId, ws), inArray(schema.contacts.ownerId, pool))).groupBy(schema.contacts.ownerId);
    const map = new Map(last.map((l) => [l.ownerId, new Date(l.at).getTime()]));
    chosen = [...pool].sort((x, y) => (map.get(x) ?? 0) - (map.get(y) ?? 0))[0]!;
  }
  await ctx.db.update(schema.contacts).set({ ownerId: chosen, updatedAt: new Date() }).where(eq(schema.contacts.id, contactId));
  const owner = members.find((m) => m.id === chosen);
  await ctx.db.insert(schema.events).values({ workspaceId: ws, contactId, name: "lead.assigned", source: "routing", properties: { owner_id: chosen, owner_name: owner?.name, rule: rule?.name ?? "default round-robin" } });
  return chosen;
}

/* ---------------- Deals & stages ---------------- */

export async function changeStage(ctx: Ctx, dealId: string, stageId: string, opts: { lostReason?: string; value?: number; position?: number } = {}) {
  const ws = ctx.workspace.id;
  const deal = await ctx.db.query.deals.findFirst({ where: and(eq(schema.deals.id, dealId), eq(schema.deals.workspaceId, ws)) });
  if (!deal) throw new ApiError(404, "not_found", "Deal not found");
  assertCanTouchDeal(ctx, deal);
  const pipeline = await ctx.db.query.pipelines.findFirst({ where: eq(schema.pipelines.id, deal.pipelineId) });
  const stage = pipeline?.stages.find((s) => s.id === stageId);
  if (!pipeline || !stage) throw new ApiError(422, "validation_failed", "Unknown stage for this pipeline");
  const from = pipeline.stages.find((s) => s.id === deal.stageId);
  if (deal.stageId === stageId) {
    if (opts.position !== undefined) await ctx.db.update(schema.deals).set({ position: opts.position }).where(eq(schema.deals.id, deal.id));
    return deal;
  }
  const kind = stage.kind ?? (/won|booked/i.test(stage.name) ? "won" : /lost/i.test(stage.name) ? "lost" : "open");
  // LEAD-007: Lost requires a reason; Won requires a value
  if (kind === "lost" && !opts.lostReason?.trim()) throw new ApiError(422, "lost_reason_required", "Moving to Lost requires a reason");
  const value = opts.value ?? deal.value;
  if (kind === "won" && !(value > 0)) throw new ApiError(422, "won_value_required", "Moving to Won requires a deal value");

  const [updated] = await ctx.db.update(schema.deals).set({
    stageId, stageChangedAt: new Date(), updatedAt: new Date(), value,
    lostReason: kind === "lost" ? opts.lostReason!.trim() : null, lostAt: kind === "lost" ? new Date() : null, wonAt: kind === "won" ? new Date() : null,
    ...(opts.position !== undefined ? { position: opts.position } : {}),
  }).where(eq(schema.deals.id, deal.id)).returning();

  // first contact for response-time metrics
  if (from && from.order === Math.min(...pipeline.stages.map((s) => s.order))) {
    await ctx.db.update(schema.contacts).set({ firstContactedAt: sql`COALESCE(${schema.contacts.firstContactedAt}, now())` }).where(eq(schema.contacts.id, deal.contactId));
  }
  const lifecycle = kind === "won" ? "customer" : kind === "lost" ? "lost" : stage.order >= 2 ? "opportunity" : "lead";
  await ctx.db.update(schema.contacts).set({ lifecycleStage: lifecycle, lastActivityAt: new Date() }).where(eq(schema.contacts.id, deal.contactId));
  await ctx.db.insert(schema.events).values({ workspaceId: ws, contactId: deal.contactId, name: "deal.stage_changed", source: ctx.actor.type, properties: { deal_id: deal.id, from: deal.stageId, from_name: from?.name, to: stageId, to_name: stage.name, by: ctx.actor.name } });
  await audit(ctx, "stage_change", "deal", deal.id, { stage: from?.name }, { stage: stage.name, value, lostReason: opts.lostReason });
  await emit(ctx.db, ws, "deal.stage_changed", { deal_id: deal.id, contact_id: deal.contactId, from: from?.name, to: stage.name, value, currency: deal.currency });
  if (kind === "won") await emit(ctx.db, ws, "deal.won", { deal_id: deal.id, contact_id: deal.contactId, value, currency: deal.currency });
  if (kind === "lost") await emit(ctx.db, ws, "deal.lost", { deal_id: deal.id, contact_id: deal.contactId, reason: opts.lostReason });

  // LEAD-008 / ADS-003: stage changes trigger conversion sync
  const eventName = stage.conversionEvent ?? (kind === "won" ? "Won" : /qualif/i.test(stage.name) ? "Qualified" : /visit|appointment|test drive|demo|consultation/i.test(stage.name) ? "SiteVisit" : null);
  if (eventName) {
    const { queueConversions } = await import("./conversions");
    await queueConversions(ctx, { dealId: deal.id, contactId: deal.contactId, eventName, value: kind === "won" ? value : 0 });
  }
  const { triggerJourneys, checkGoals } = await import("./journeys");
  await triggerJourneys(ctx, "stage_changed", deal.contactId, { stage: stageId, stage_name: stage.name, pipeline: pipeline.id });
  await checkGoals(ctx, deal.contactId, "stage_reached", stageId);
  return updated!;
}

export function assertCanTouchDeal(ctx: Ctx, deal: { ownerId: string | null }) {
  if (ctx.perms.contacts === "C:assigned" && deal.ownerId !== ctx.user?.id) throw new ApiError(403, "forbidden", "Sales reps can only change their assigned leads");
  if (ctx.perms.contacts !== "C" && ctx.perms.contacts !== "C:assigned") throw new ApiError(403, "forbidden", "You cannot edit deals");
}

/* ---------------- Activities & tasks (LEAD-005/006) ---------------- */

export async function createActivity(ctx: Ctx, input: { contactId?: string | null; dealId?: string | null; userId?: string | null; type: string; title: string; body?: string | null; dueAt?: Date | null; outcome?: string | null; durationSec?: number | null; recordingUrl?: string | null; completed?: boolean; externalRef?: string | null }) {
  const ws = ctx.workspace.id;
  const userId = input.userId ?? ctx.user?.id ?? null;
  const [a] = await ctx.db.insert(schema.activities).values({
    workspaceId: ws, contactId: input.contactId ?? null, dealId: input.dealId ?? null, userId, type: input.type, title: input.title, body: input.body ?? null,
    dueAt: input.dueAt ?? null, outcome: input.outcome ?? null, durationSec: input.durationSec ?? null, recordingUrl: input.recordingUrl ?? null,
    completedAt: input.completed ? new Date() : null, calendarEventId: input.externalRef ?? null, createdBy: ctx.actor.type === "user" ? ctx.actor.id : null,
  }).returning();
  if (input.contactId) {
    const touches = ["call", "meeting", "visit", "email", "whatsapp"].includes(input.type) && input.completed;
    await ctx.db.update(schema.contacts).set({ lastActivityAt: new Date(), ...(touches ? { firstContactedAt: sql`COALESCE(${schema.contacts.firstContactedAt}, now())` } : {}) }).where(eq(schema.contacts.id, input.contactId));
  }
  // calendar sync for scheduled work
  if (input.dueAt && ["task", "call", "meeting", "visit"].includes(input.type) && !input.completed) {
    await enqueue(ctx.db, "calendar.push", { workspaceId: ws, activityId: a!.id }, { workspaceId: ws });
    await enqueue(ctx.db, "task.reminder", { workspaceId: ws, activityId: a!.id }, { workspaceId: ws, runAt: new Date(Math.max(Date.now(), input.dueAt.getTime() - 15 * 60000)) });
  }
  await audit(ctx, "create", "activity", a!.id, undefined, { type: a!.type, title: a!.title });
  await emit(ctx.db, ws, "activity.created", { activity: a });
  if (userId && userId !== ctx.user?.id && input.dueAt) await notifyUser(ctx, userId, "task", `New task: ${input.title}`, undefined, input.contactId ? `/contacts/${input.contactId}` : "/tasks");
  return a!;
}

export async function completeActivity(ctx: Ctx, id: string, outcome?: string) {
  const [a] = await ctx.db.update(schema.activities).set({ completedAt: new Date(), outcome: outcome ?? null, updatedAt: new Date() })
    .where(and(eq(schema.activities.id, id), eq(schema.activities.workspaceId, ctx.workspace.id))).returning();
  if (!a) throw new ApiError(404, "not_found", "Activity not found");
  if (a.contactId && ["call", "meeting", "visit"].includes(a.type)) await ctx.db.update(schema.contacts).set({ firstContactedAt: sql`COALESCE(${schema.contacts.firstContactedAt}, now())`, lastActivityAt: new Date() }).where(eq(schema.contacts.id, a.contactId));
  await audit(ctx, "complete", "activity", id, undefined, { outcome });
  return a;
}

/** Twilio recording callback → recording on the timeline + AI summary (LEAD-006, AI-007). */
export async function logCallRecording(ctx: Ctx, callSid: string, recordingUrl: string, durationSec: number) {
  const a = await ctx.db.query.activities.findFirst({ where: and(eq(schema.activities.workspaceId, ctx.workspace.id), eq(schema.activities.calendarEventId, callSid)) });
  if (!a) return;
  await ctx.db.update(schema.activities).set({ recordingUrl, durationSec, completedAt: a.completedAt ?? new Date() }).where(eq(schema.activities.id, a.id));
  await enqueue(ctx.db, "ai.summarize_call", { workspaceId: ctx.workspace.id, activityId: a.id }, { workspaceId: ctx.workspace.id });
}

/* ---------------- SLA (LEAD-004) ---------------- */

export async function checkSla(ctx: Ctx) {
  const ws = ctx.workspace.id;
  const breached = await ctx.db.select({ d: schema.deals, c: schema.contacts }).from(schema.deals).innerJoin(schema.contacts, eq(schema.contacts.id, schema.deals.contactId))
    .where(and(eq(schema.deals.workspaceId, ws), isNull(schema.deals.slaBreachedAt), isNull(schema.contacts.firstContactedAt), isNull(schema.deals.wonAt), isNull(schema.deals.lostAt), sql`${schema.deals.slaDueAt} < now()`)).limit(100);
  for (const { d, c } of breached) {
    const pipeline = await ctx.db.query.pipelines.findFirst({ where: eq(schema.pipelines.id, d.pipelineId) });
    await ctx.db.update(schema.deals).set({ slaBreachedAt: new Date() }).where(eq(schema.deals.id, d.id));
    await ctx.db.insert(schema.events).values({ workspaceId: ws, contactId: c.id, name: "sla.breached", source: "system", properties: { deal_id: d.id, owner_id: d.ownerId, sla_minutes: pipeline?.slaMinutes } });
    if (pipeline?.slaAction === "reassign") {
      const prev = d.ownerId;
      await ctx.db.update(schema.contacts).set({ ownerId: null }).where(eq(schema.contacts.id, c.id));
      const next = await routeLead(ctx, c.id, { source: c.source, project: c.project, territory: c.territory });
      if (next && next !== prev) {
        await ctx.db.update(schema.deals).set({ ownerId: next, slaDueAt: new Date(Date.now() + (pipeline.slaMinutes ?? 5) * 60000), slaBreachedAt: null }).where(eq(schema.deals.id, d.id));
        await notifyUser(ctx, next, "sla", `Reassigned lead: ${fullName(c)}`, `Previous owner missed the ${pipeline.slaMinutes}-minute SLA`, `/contacts/${c.id}`);
      }
    }
    await notifyAdmins(ctx, "sla", `SLA breached: ${fullName(c)}`, `Not contacted within ${pipeline?.slaMinutes ?? 5} minutes`, `/contacts/${c.id}`, ["marketing_manager", "workspace_admin"]);
  }
  return breached.length;
}
