/**
 * Journey engine (FLOW-001…007). Durable state machine on Postgres: each run is pinned to the version it
 * entered on (FLOW-004), waits are persisted (resume_at) and drained by the worker, every step is logged to the
 * run and to per-node stats (FLOW-006). Quiet hours and frequency caps are enforced by the messaging layer.
 */
import { and, eq, inArray, lte, sql } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { systemCtx } from "@/lib/auth";
import { enqueue } from "@/lib/jobs";
import { emit } from "@/lib/webhooks";
import { audit } from "@/lib/audit";
import { ApiError } from "@/lib/api";
import { renderTemplate } from "@/lib/util";
import type { JourneyGraph, JourneyNode, JourneyTrigger, JourneyGoal } from "@/db/schema";
import { contactMatches } from "./segments";

export const TRIGGERS: { type: JourneyTrigger["type"]; label: string; config?: string }[] = [
  { type: "contact_created", label: "Contact created" },
  { type: "field_changed", label: "Field changed", config: "field" },
  { type: "stage_changed", label: "Deal stage changed", config: "stage" },
  { type: "form_submitted", label: "Form submitted", config: "formId" },
  { type: "event_received", label: "Event received", config: "event" },
  { type: "tag_added", label: "Tag added", config: "tag" },
  { type: "date_based", label: "Date-based (field anniversary / reminder)", config: "field" },
  { type: "webhook", label: "Inbound webhook / API enroll" },
  { type: "manual", label: "Manual enrolment" },
];

export const ACTIONS = [
  { key: "send_message", label: "Send message" }, { key: "assign", label: "Assign owner" }, { key: "update_field", label: "Update field" },
  { key: "add_tag", label: "Add tag" }, { key: "remove_tag", label: "Remove tag" }, { key: "create_task", label: "Create task" },
  { key: "move_stage", label: "Move deal stage" }, { key: "http_request", label: "HTTP request" }, { key: "notify_team", label: "Notify team" },
  { key: "start_ai_agent", label: "Start AI qualification agent" },
];

function triggerMatches(t: JourneyTrigger, type: string, payload: Record<string, unknown>) {
  if (t.type !== type) return false;
  const c = t.config ?? {};
  if (type === "stage_changed" && c.stage && c.stage !== payload.stage) return false;
  if (type === "tag_added" && c.tag && String(c.tag).toLowerCase() !== String(payload.tag).toLowerCase()) return false;
  if (type === "field_changed" && c.field && c.field !== payload.field) return false;
  if (type === "form_submitted" && c.formId && c.formId !== payload.formId) return false;
  if (type === "event_received" && c.event && c.event !== payload.event) return false;
  return true;
}

export async function triggerJourneys(ctx: Ctx, type: JourneyTrigger["type"], contactId: string, payload: Record<string, unknown>) {
  const live = await ctx.db.select().from(schema.journeys).where(and(eq(schema.journeys.workspaceId, ctx.workspace.id), eq(schema.journeys.status, "live")));
  let n = 0;
  for (const j of live) if (triggerMatches(j.trigger, type, payload)) if (await enroll(ctx, j.id, contactId, payload)) n++;
  return n;
}

export async function enroll(ctx: Ctx, journeyId: string, contactId: string, payload: Record<string, unknown> = {}) {
  const j = await ctx.db.query.journeys.findFirst({ where: and(eq(schema.journeys.id, journeyId), eq(schema.journeys.workspaceId, ctx.workspace.id)) });
  if (!j) throw new ApiError(404, "not_found", "Journey not found");
  if (j.status !== "live") throw new ApiError(409, "conflict", "Journey is not live");
  const contact = await ctx.db.query.contacts.findFirst({ where: and(eq(schema.contacts.id, contactId), eq(schema.contacts.workspaceId, ctx.workspace.id)) });
  if (!contact || contact.deletedAt) return null;
  if (!j.trigger.config?.allowReentry) {
    const active = await ctx.db.query.journeyRuns.findFirst({ where: and(eq(schema.journeyRuns.journeyId, j.id), eq(schema.journeyRuns.contactId, contactId), inArray(schema.journeyRuns.status, ["active", "waiting"])) });
    if (active) return null;
    if (j.trigger.config?.once) {
      const ever = await ctx.db.query.journeyRuns.findFirst({ where: and(eq(schema.journeyRuns.journeyId, j.id), eq(schema.journeyRuns.contactId, contactId)) });
      if (ever) return null;
    }
  }
  const v = await ctx.db.query.journeyVersions.findFirst({ where: and(eq(schema.journeyVersions.journeyId, j.id), eq(schema.journeyVersions.version, j.version)) });
  if (!v) return null;
  const start = v.graph.nodes.find((n) => n.type === "trigger");
  const first = start ? nextNode(v.graph, start.id) : v.graph.nodes[0]?.id;
  const [run] = await ctx.db.insert(schema.journeyRuns).values({ workspaceId: ctx.workspace.id, journeyId: j.id, version: j.version, contactId, currentStep: first ?? null, status: "active", log: [{ step: "trigger", at: new Date().toISOString(), status: "entered", detail: JSON.stringify(payload).slice(0, 200) }] }).returning();
  await bumpStat(ctx, j.id, "trigger", "entered");
  await ctx.db.insert(schema.events).values({ workspaceId: ctx.workspace.id, contactId, name: "journey.entered", source: "journey", properties: { journey: j.name, journey_id: j.id, version: j.version } });
  await enqueue(ctx.db, "journey.step", { workspaceId: ctx.workspace.id, runId: run!.id }, { workspaceId: ctx.workspace.id });
  return run!;
}

function nextNode(g: JourneyGraph, from: string, handle?: string) {
  const edges = g.edges.filter((e) => e.source === from);
  const e = handle ? edges.find((x) => x.sourceHandle === handle) ?? null : edges[0];
  return e?.target ?? null;
}

async function bumpStat(ctx: Pick<Ctx, "db">, journeyId: string, nodeId: string, field: "entered" | "completed" | "failed") {
  // atomic per-node counter: stats[nodeId][field] += 1
  await ctx.db.execute(sql`UPDATE journeys SET stats = COALESCE(stats, '{}'::jsonb) || jsonb_build_object(${nodeId}::text,
    COALESCE(stats -> ${nodeId}::text, '{"entered":0,"completed":0,"failed":0}'::jsonb)
      || jsonb_build_object(${field}::text, COALESCE((stats -> ${nodeId}::text ->> ${field}::text)::int, 0) + 1))
    WHERE id = ${journeyId}`);
}

/** Execute a run until it waits, finishes or fails. */
export async function advanceRun(runId: string) {
  const { getDb } = await import("@/db");
  const db = await getDb();
  const run = await db.query.journeyRuns.findFirst({ where: eq(schema.journeyRuns.id, runId) });
  if (!run || !["active", "waiting"].includes(run.status)) return;
  const ctx = await systemCtx(run.workspaceId, { type: "system", id: null, name: "Journey" });
  const journey = await db.query.journeys.findFirst({ where: eq(schema.journeys.id, run.journeyId) });
  const v = await db.query.journeyVersions.findFirst({ where: and(eq(schema.journeyVersions.journeyId, run.journeyId), eq(schema.journeyVersions.version, run.version)) });
  if (!journey || !v) return;
  if (journey.status === "archived") {
    await db.update(schema.journeyRuns).set({ status: "exited", updatedAt: new Date() }).where(eq(schema.journeyRuns.id, run.id));
    return;
  }
  const log = [...run.log];
  let step = run.currentStep;
  let guard = 0;
  const finish = async (status: string, detail?: string) => {
    log.push({ step: step ?? "end", at: new Date().toISOString(), status, detail });
    await db.update(schema.journeyRuns).set({ status, currentStep: step, log, resumeAt: null, updatedAt: new Date() }).where(eq(schema.journeyRuns.id, run.id));
    if (status === "completed") {
      await db.insert(schema.events).values({ workspaceId: run.workspaceId, contactId: run.contactId, name: "journey.completed", source: "journey", properties: { journey: journey.name, journey_id: journey.id } });
      await emit(db, run.workspaceId, "journey.completed", { journey_id: journey.id, run_id: run.id, contact_id: run.contactId });
    }
    if (status === "failed") await emit(db, run.workspaceId, "journey.failed", { journey_id: journey.id, run_id: run.id, contact_id: run.contactId, error: detail });
  };

  while (step && guard++ < 50) {
    const node = v.graph.nodes.find((n) => n.id === step);
    if (!node) return finish("failed", `Missing node ${step}`);
    // re-entering a wait node whose time has passed → continue past it
    if (node.type === "wait" && run.status === "waiting" && run.currentStep === node.id && run.resumeAt && run.resumeAt <= new Date()) {
      run.status = "active";
      log.push({ step: node.id, at: new Date().toISOString(), status: "completed", detail: "wait finished" });
      await bumpStat(ctx, journey.id, node.id, "completed");
      step = nextNode(v.graph, node.id);
      continue;
    }
    await bumpStat(ctx, journey.id, node.id, "entered");
    try {
      const r = await execNode(ctx, node, run.contactId, v.graph, journey.id);
      if (r.waitUntil) {
        log.push({ step: node.id, at: new Date().toISOString(), status: "waiting", detail: r.detail ?? `until ${r.waitUntil.toISOString()}` });
        await db.update(schema.journeyRuns).set({ status: "waiting", currentStep: node.id, resumeAt: r.waitUntil, log, updatedAt: new Date() }).where(eq(schema.journeyRuns.id, run.id));
        return;
      }
      if (r.deferredNode) {
        // quiet hours: retry the same node later
        log.push({ step: node.id, at: new Date().toISOString(), status: "deferred", detail: r.detail });
        await db.update(schema.journeyRuns).set({ status: "waiting", currentStep: node.id, resumeAt: r.deferredNode, log, updatedAt: new Date() }).where(eq(schema.journeyRuns.id, run.id));
        await db.update(schema.journeyRuns).set({ log }).where(eq(schema.journeyRuns.id, run.id));
        return;
      }
      log.push({ step: node.id, at: new Date().toISOString(), status: "completed", detail: r.detail });
      await bumpStat(ctx, journey.id, node.id, "completed");
      if (r.end) return finish(r.end, r.detail);
      step = r.next === undefined ? nextNode(v.graph, node.id) : r.next;
    } catch (e) {
      await bumpStat(ctx, journey.id, node.id, "failed");
      return finish("failed", e instanceof Error ? e.message : String(e));
    }
  }
  return finish("completed");
}

type StepResult = { next?: string | null; waitUntil?: Date; deferredNode?: Date; detail?: string; end?: "completed" | "exited" };

async function execNode(ctx: Ctx, node: JourneyNode, contactId: string, g: JourneyGraph, journeyId: string): Promise<StepResult> {
  const d = node.data as Record<string, any>;
  switch (node.type) {
    case "wait": {
      const ms = (Number(d.days ?? 0) * 1440 + Number(d.hours ?? 0) * 60 + Number(d.minutes ?? 0)) * 60000;
      return { waitUntil: new Date(Date.now() + Math.max(ms, 0)), detail: `wait ${d.days ?? 0}d ${d.hours ?? 0}h ${d.minutes ?? 0}m` };
    }
    case "condition": {
      const ok = await contactMatches(ctx, contactId, { match: d.match ?? "all", rules: d.rules ?? [] });
      return { next: nextNode(g, node.id, ok ? "yes" : "no"), detail: ok ? "yes" : "no" };
    }
    case "split": {
      const pctA = Number(d.percent ?? 50);
      const branch = Math.random() * 100 < pctA ? "a" : "b";
      return { next: nextNode(g, node.id, branch), detail: `variant ${branch.toUpperCase()}` };
    }
    case "goal":
      return { end: "completed", detail: "goal node" };
    case "exit":
      return { end: "exited", detail: "exit node" };
    case "trigger":
      return {};
    case "action":
      return execAction(ctx, d, contactId, journeyId);
  }
  return {};
}

async function execAction(ctx: Ctx, d: Record<string, any>, contactId: string, journeyId: string): Promise<StepResult> {
  const contact = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, contactId) }))!;
  switch (d.action) {
    case "send_message": {
      const { sendMessage } = await import("./messaging");
      const r = await sendMessage(ctx, { contactId, channel: d.channel ?? "whatsapp", body: d.body, subject: d.subject, templateId: d.templateId || null, source: "journey" });
      if (r.deferredUntil) return { deferredNode: r.deferredUntil, detail: "quiet hours" };
      const status = r.message?.status ?? (r.blocked ? "blocked" : "skipped");
      if (status === "failed") throw new Error(r.message?.error ?? "send failed");
      return { detail: `${d.channel}: ${status}${r.blocked ? ` (${r.blocked})` : r.message?.error ? ` (${r.message.error})` : ""}` };
    }
    case "assign": {
      if (d.userId) {
        await ctx.db.update(schema.contacts).set({ ownerId: d.userId }).where(eq(schema.contacts.id, contactId));
        await ctx.db.update(schema.deals).set({ ownerId: d.userId }).where(and(eq(schema.deals.contactId, contactId), sql`${schema.deals.wonAt} IS NULL AND ${schema.deals.lostAt} IS NULL`));
        return { detail: `assigned to ${d.userId}` };
      }
      const { routeLead } = await import("./leads");
      const o = await routeLead(ctx, contactId, { source: contact.source, project: contact.project, territory: contact.territory });
      return { detail: `routed to ${o ?? "nobody"}` };
    }
    case "update_field": {
      const { updateContact } = await import("./contacts");
      const value = renderTemplate(String(d.value ?? ""), { ...contact, custom: contact.customFields });
      if (String(d.field).startsWith("custom.")) await updateContact(ctx, contactId, { customFields: { [String(d.field).slice(7)]: value } });
      else {
        const map: Record<string, string> = { lifecycle_stage: "lifecycleStage", city: "city", territory: "territory", project: "project", score: "score" };
        const k = map[d.field] ?? d.field;
        await updateContact(ctx, contactId, { [k]: k === "score" ? Number(value) : value } as never);
      }
      return { detail: `${d.field} = ${value}` };
    }
    case "add_tag": {
      const { addTags } = await import("./contacts");
      await addTags(ctx, contactId, String(d.tag).split(",").map((t) => t.trim()).filter(Boolean));
      return { detail: `tag ${d.tag}` };
    }
    case "remove_tag": {
      await ctx.db.update(schema.contacts).set({ tags: contact.tags.filter((t) => t !== d.tag) }).where(eq(schema.contacts.id, contactId));
      return { detail: `removed ${d.tag}` };
    }
    case "create_task": {
      const { createActivity } = await import("./leads");
      await createActivity(ctx, { contactId, type: d.taskType ?? "task", title: renderTemplate(d.title ?? "Follow up", { name: contact.firstName }), userId: d.userId || contact.ownerId, dueAt: new Date(Date.now() + Number(d.dueInHours ?? 24) * 3600000) });
      return { detail: `task: ${d.title}` };
    }
    case "move_stage": {
      const deal = await ctx.db.query.deals.findFirst({ where: and(eq(schema.deals.contactId, contactId), sql`${schema.deals.wonAt} IS NULL AND ${schema.deals.lostAt} IS NULL`) });
      if (!deal) return { detail: "no open deal" };
      const { changeStage } = await import("./leads");
      await changeStage(ctx, deal.id, d.stageId, { lostReason: d.lostReason });
      return { detail: `stage → ${d.stageId}` };
    }
    case "http_request": {
      const vars = { contact: { id: contact.id, first_name: contact.firstName, last_name: contact.lastName, phone: contact.phones[0], email: contact.emails[0], city: contact.city, project: contact.project, tags: contact.tags, custom: contact.customFields }, workspace_id: ctx.workspace.id };
      const url = renderTemplate(String(d.url), vars);
      if (!/^https:\/\//.test(url) && process.env.NODE_ENV === "production") throw new Error("HTTP actions require https URLs");
      const headers = Object.fromEntries(String(d.headers ?? "").split("\n").map((l) => l.split(":")).filter((p) => p.length >= 2).map(([k, ...v]) => [k!.trim(), renderTemplate(v.join(":").trim(), vars)]));
      const res = await fetch(url, { method: d.method ?? "POST", headers: { "Content-Type": "application/json", ...headers }, body: (d.method ?? "POST") === "GET" ? undefined : renderTemplate(String(d.body ?? JSON.stringify(vars)), vars), signal: AbortSignal.timeout(15000) });
      if (!res.ok) throw new Error(`HTTP ${res.status} from ${new URL(url).host}`);
      return { detail: `HTTP ${res.status}` };
    }
    case "notify_team": {
      const { notifyTeam } = await import("./notify");
      const { fullName } = await import("@/lib/util");
      await notifyTeam(ctx, renderTemplate(d.title ?? "Journey alert: {{name}}", { name: fullName(contact) }), d.body, `/contacts/${contactId}`, d.userIds?.length ? d.userIds : contact.ownerId ? [contact.ownerId] : undefined);
      return { detail: "team notified" };
    }
    case "start_ai_agent": {
      const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.contactId, contactId), eq(schema.conversations.channel, d.channel ?? "whatsapp")) });
      if (conv) await ctx.db.update(schema.conversations).set({ aiAgentActive: true }).where(eq(schema.conversations.id, conv.id));
      await enqueue(ctx.db, "ai.agent_start", { workspaceId: ctx.workspace.id, contactId, channel: d.channel ?? "whatsapp" }, { workspaceId: ctx.workspace.id });
      return { detail: "AI agent started" };
    }
  }
  throw new Error(`Unknown action ${d.action}`);
}

/** FLOW-005: a contact reaching the goal leaves the journey */
export async function checkGoals(ctx: Ctx, contactId: string, type: JourneyGoal["type"], value: string) {
  const runs = await ctx.db.select({ r: schema.journeyRuns, v: schema.journeyVersions }).from(schema.journeyRuns)
    .innerJoin(schema.journeyVersions, and(eq(schema.journeyVersions.journeyId, schema.journeyRuns.journeyId), eq(schema.journeyVersions.version, schema.journeyRuns.version)))
    .where(and(eq(schema.journeyRuns.contactId, contactId), inArray(schema.journeyRuns.status, ["active", "waiting"])));
  for (const { r, v } of runs) {
    if (v.goal && v.goal.type === type && String(v.goal.value).toLowerCase() === String(value).toLowerCase()) {
      await ctx.db.update(schema.journeyRuns).set({ status: "completed", log: [...r.log, { step: "goal", at: new Date().toISOString(), status: "goal reached", detail: `${type}=${value}` }], updatedAt: new Date() }).where(eq(schema.journeyRuns.id, r.id));
      await bumpStat(ctx, r.journeyId, "goal", "completed");
      await emit(ctx.db, ctx.workspace.id, "journey.completed", { journey_id: r.journeyId, run_id: r.id, contact_id: contactId, reason: "goal" });
    }
  }
}

/** FLOW-004: publishing creates an immutable version; in-flight runs finish on theirs. */
export async function publishJourney(ctx: Ctx, journeyId: string) {
  const j = await ctx.db.query.journeys.findFirst({ where: and(eq(schema.journeys.id, journeyId), eq(schema.journeys.workspaceId, ctx.workspace.id)) });
  if (!j) throw new ApiError(404, "not_found", "Journey not found");
  validateGraph(j.graph);
  const latest = await ctx.db.select({ v: sql<number>`COALESCE(max(version), 0)::int` }).from(schema.journeyVersions).where(eq(schema.journeyVersions.journeyId, j.id));
  const version = (latest[0]?.v ?? 0) + 1;
  await ctx.db.insert(schema.journeyVersions).values({ workspaceId: ctx.workspace.id, journeyId: j.id, version, trigger: j.trigger, graph: j.graph, goal: j.goal ?? null, createdBy: ctx.user?.id ?? null });
  const [updated] = await ctx.db.update(schema.journeys).set({ version, status: "live", updatedAt: new Date() }).where(eq(schema.journeys.id, j.id)).returning();
  await audit(ctx, "publish", "journey", j.id, { version: j.version }, { version });
  return updated!;
}

export function validateGraph(g: JourneyGraph) {
  if (!g.nodes.some((n) => n.type === "trigger")) throw new ApiError(422, "validation_failed", "Journey needs a trigger node");
  for (const n of g.nodes) {
    if (n.type === "action" && !n.data.action) throw new ApiError(422, "validation_failed", `Action node "${n.data.label ?? n.id}" has no action selected`);
    if (n.type === "action" && n.data.action === "send_message" && !n.data.body && !n.data.templateId) throw new ApiError(422, "validation_failed", `Send message node "${n.data.label ?? n.id}" needs a message or template`);
    if (n.type === "action" && n.data.action === "http_request" && !n.data.url) throw new ApiError(422, "validation_failed", "HTTP request node needs a URL");
    if (n.type === "condition" && !g.edges.some((e) => e.source === n.id)) throw new ApiError(422, "validation_failed", "Condition node needs yes/no branches");
  }
}

/** Resume waiting runs whose time has come (worker). */
export async function resumeDueRuns(limit = 200) {
  const { getDb } = await import("@/db");
  const db = await getDb();
  const due = await db.select({ id: schema.journeyRuns.id, ws: schema.journeyRuns.workspaceId }).from(schema.journeyRuns).where(and(eq(schema.journeyRuns.status, "waiting"), lte(schema.journeyRuns.resumeAt, new Date()))).limit(limit);
  for (const r of due) await enqueue(db, "journey.step", { workspaceId: r.ws, runId: r.id }, { workspaceId: r.ws, idempotencyKey: `resume:${r.id}:${Math.floor(Date.now() / 60000)}` });
  return due.length;
}

/** Date-based triggers: enrol contacts whose date field (custom) is today + offset (daily cron). */
export async function runDateTriggers(ctx: Ctx) {
  const live = await ctx.db.select().from(schema.journeys).where(and(eq(schema.journeys.workspaceId, ctx.workspace.id), eq(schema.journeys.status, "live")));
  let n = 0;
  for (const j of live.filter((x) => x.trigger.type === "date_based")) {
    const field = String(j.trigger.config?.field ?? "");
    const offset = Number(j.trigger.config?.offsetDays ?? 0);
    if (!field) continue;
    const target = new Date(Date.now() - offset * 86400000).toISOString().slice(5, 10); // MM-DD (anniversary semantics)
    const exact = j.trigger.config?.yearly === false;
    const day = new Date(Date.now() - offset * 86400000).toISOString().slice(0, 10);
    const col = field.startsWith("custom.") ? sql`(${schema.contacts.customFields} ->> ${field.slice(7)})` : sql`${schema.contacts.createdAt}::date::text`;
    const rows = await ctx.db.select({ id: schema.contacts.id }).from(schema.contacts).where(and(eq(schema.contacts.workspaceId, ctx.workspace.id), sql`${schema.contacts.deletedAt} IS NULL`, exact ? sql`substr(${col}, 1, 10) = ${day}` : sql`substr(${col}, 6, 5) = ${target}`));
    for (const r of rows) if (await enroll(ctx, j.id, r.id, { date: day })) n++;
  }
  return n;
}
