/** Registers every background job type. Imported lazily by runJobs(). */
import { and, eq, isNull } from "drizzle-orm";
import { getDb, schema } from "@/db";
import { systemCtx } from "./auth";
import { registerJob, enqueue } from "./jobs";
import { deliverWebhook } from "./webhooks";

const ws = (p: Record<string, unknown>) => String(p.workspaceId);

registerJob("webhook.deliver", async (p) => deliverWebhook(await getDb(), String(p.deliveryId)));

registerJob("conversion.send", async (p) => {
  const { sendConversion } = await import("./services/conversions");
  await sendConversion(await systemCtx(ws(p)), String(p.conversionId), String(p.integrationId));
});

registerJob("journey.step", async (p) => {
  const { advanceRun } = await import("./services/journeys");
  await advanceRun(String(p.runId));
});

registerJob("broadcast.process", async (p) => {
  const { processBroadcast } = await import("./services/messaging");
  const ctx = await systemCtx(ws(p), { type: "system", id: null, name: "Broadcast" });
  const r = await processBroadcast(ctx, String(p.broadcastId));
  if (!r.done) await enqueue(ctx.db, "broadcast.process", p, { workspaceId: ws(p), runAt: r.runAt });
});

registerJob("integration.sync", async (p) => {
  const { syncIntegration } = await import("@/connectors");
  const ctx = await systemCtx(ws(p));
  const i = await ctx.db.query.integrations.findFirst({ where: eq(schema.integrations.id, String(p.integrationId)) });
  if (i) await syncIntegration(ctx, i);
});

registerJob("calendar.push", async (p) => {
  const ctx = await systemCtx(ws(p));
  const a = await ctx.db.query.activities.findFirst({ where: eq(schema.activities.id, String(p.activityId)) });
  if (!a?.dueAt || a.calendarEventId) return;
  const { findIntegration, pushVia } = await import("@/connectors");
  const cal = await findIntegration(ctx, "google_calendar");
  if (!cal) return;
  const contact = a.contactId ? await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, a.contactId) }) : null;
  const owner = a.userId ? await ctx.db.query.users.findFirst({ where: eq(schema.users.id, a.userId) }) : null;
  const r = await pushVia(ctx, cal, "event", { title: `${a.title}${contact ? ` — ${[contact.firstName, contact.lastName].filter(Boolean).join(" ")}` : ""}`, description: `${a.body ?? ""}\n${process.env.APP_URL ?? ""}/contacts/${a.contactId ?? ""}`, start: a.dueAt.toISOString(), durationMin: a.type === "visit" ? 60 : 30, attendee: owner?.email });
  await ctx.db.update(schema.activities).set({ calendarEventId: String(r.eventId ?? "") }).where(eq(schema.activities.id, a.id));
});

registerJob("task.reminder", async (p) => {
  const ctx = await systemCtx(ws(p));
  const a = await ctx.db.query.activities.findFirst({ where: eq(schema.activities.id, String(p.activityId)) });
  if (!a || a.completedAt || a.reminderSentAt || !a.userId) return;
  const { notifyUser } = await import("./services/notify");
  await notifyUser(ctx, a.userId, "reminder", `Due soon: ${a.title}`, a.dueAt ? `Due ${a.dueAt.toISOString().slice(11, 16)} UTC` : undefined, a.contactId ? `/contacts/${a.contactId}` : "/tasks");
  await ctx.db.update(schema.activities).set({ reminderSentAt: new Date() }).where(eq(schema.activities.id, a.id));
  const { emit } = await import("./webhooks");
  await emit(ctx.db, ctx.workspace.id, "task.due", { activity_id: a.id, user_id: a.userId, due_at: a.dueAt });
});

registerJob("notify.slack", async (p) => {
  const ctx = await systemCtx(ws(p));
  const { findIntegration, pushVia } = await import("@/connectors");
  const slack = await findIntegration(ctx, "slack");
  if (slack) await pushVia(ctx, slack, "notify", { title: p.title, body: p.body, link: p.link ? `${process.env.APP_URL ?? ""}${p.link}` : "" });
});

registerJob("segments.refresh", async (p) => {
  const { refreshSegments } = await import("./services/segments");
  await refreshSegments(await systemCtx(ws(p)));
});

registerJob("audience.sync", async (p) => {
  const ctx = await systemCtx(ws(p));
  const seg = await ctx.db.query.segments.findFirst({ where: eq(schema.segments.id, String(p.segmentId)) });
  if (!seg) return;
  const { segmentMemberIds } = await import("./services/segments");
  const ids = await segmentMemberIds(ctx, seg.id);
  const contacts = ids.length ? await ctx.db.query.contacts.findMany({ where: (c, { inArray }) => inArray(c.id, ids) }) : [];
  const members = contacts.map((c) => ({ email: c.emails[0], phone: c.phones[0] }));
  const { findIntegration, pushVia } = await import("@/connectors");
  const sync = { ...seg.audienceSync } as Record<string, unknown>;
  for (const [flag, provider] of [["meta", "meta"], ["google", "google_ads"]] as const) {
    if (!seg.audienceSync[flag]) continue;
    const integ = await findIntegration(ctx, provider);
    if (!integ) continue;
    const r = await pushVia(ctx, integ, "audience", { name: `TP · ${seg.name}`, members, audienceId: sync[`${flag}AudienceId`] });
    sync[`${flag}AudienceId`] = r.audienceId;
  }
  sync.lastSyncAt = new Date().toISOString();
  await ctx.db.update(schema.segments).set({ audienceSync: sync as never }).where(eq(schema.segments.id, seg.id));
});

registerJob("ai.agent_reply", async (p) => {
  const { agentReply } = await import("./ai/features");
  await agentReply(await systemCtx(ws(p), { type: "agent", id: "qualification-agent", name: "AI qualification agent" }), String(p.conversationId));
});

registerJob("ai.agent_start", async (p) => {
  const { startAgent } = await import("./ai/features");
  await startAgent(await systemCtx(ws(p), { type: "agent", id: "qualification-agent", name: "AI qualification agent" }), String(p.contactId), String(p.channel ?? "whatsapp"));
});

registerJob("ai.summarize_call", async (p) => {
  const { summarizeActivity } = await import("./ai/features");
  await summarizeActivity(await systemCtx(ws(p), { type: "agent", id: "summarizer", name: "AI summarizer" }), String(p.activityId));
});

registerJob("import.contacts", async (p) => {
  const { processImport } = await import("./services/import");
  await processImport(await systemCtx(ws(p)), p);
});

/* ---------------- Module 11: social inbox (spec §10) ---------------- */

const socialCtx = (p: Record<string, unknown>, name = "Social inbox") => systemCtx(ws(p), { type: "system", id: null, name });
registerJob("social.backfill", async (p) => {
  const { runBackfill } = await import("./services/social-accounts");
  await runBackfill(await socialCtx(p, "Social backfill"), String(p.accountId));
});
registerJob("social.poll", async (p) => {
  const { pollAccount } = await import("./services/social-accounts");
  await pollAccount(await socialCtx(p, "Social poller"), String(p.accountId));
});
registerJob("social.meta_event", async (p) => {
  const { handleMetaEvents } = await import("./services/social-accounts");
  await handleMetaEvents(await socialCtx(p, "Meta webhook"), p.events as never);
});
registerJob("integration.webhook", async (p) => {
  // app-level Meta webhook → existing connector handler (lead ads, WhatsApp) for the owning workspace
  const { getConnector } = await import("@/connectors");
  const ctx = await socialCtx(p, "Meta webhook");
  const integ = await ctx.db.query.integrations.findFirst({ where: and(eq(schema.integrations.workspaceId, ws(p)), eq(schema.integrations.provider, String(p.provider))) });
  await getConnector(String(p.provider))?.handleWebhook?.(ctx, integ ?? null, p.body, new Headers());
});
registerJob("social.ai.classify", async (p) => {
  const { classifyComment } = await import("./ai/social");
  await classifyComment(await systemCtx(ws(p), { type: "agent", id: "social-ai", name: "Social AI" }), String(p.commentId));
});
registerJob("social.ai.review_draft", async (p) => {
  const { draftReviewReply } = await import("./ai/social");
  await draftReviewReply(await systemCtx(ws(p), { type: "agent", id: "social-ai", name: "Social AI" }), String(p.reviewId));
});
registerJob("social.ai.summary", async (p) => {
  const { summarizeSocialConversation } = await import("./ai/social");
  await summarizeSocialConversation(await systemCtx(ws(p), { type: "agent", id: "summarizer", name: "AI summarizer" }), String(p.conversationId));
});

/* ---------------- periodic routines (called from cron routes) ---------------- */

export async function everyMinute() {
  const db = await getDb();
  const { resumeDueRuns } = await import("./services/journeys");
  await resumeDueRuns();
  const all = await db.select({ id: schema.workspaces.id }).from(schema.workspaces);
  const { checkSla } = await import("./services/leads");
  const { publishDuePosts } = await import("./services/content");
  for (const w of all) {
    const ctx = await systemCtx(w.id);
    await checkSla(ctx).catch((e) => console.error("[sla]", e));
    await publishDuePosts(ctx).catch((e) => console.error("[publish]", e));
    // Module 11: snooze wake-ups, SLA breaches/escalation, lock release, polling schedule
    const { socialMinute } = await import("./services/social");
    const { enqueuePolls } = await import("./services/social-accounts");
    await socialMinute(ctx).catch((e) => console.error("[social.sla]", e));
    await enqueuePolls(ctx).catch((e) => console.error("[social.poll]", e));
    // segment counts stay < 5 minutes stale (CDP-006)
    if (new Date().getUTCMinutes() % 4 === 0) await enqueue(db, "segments.refresh", { workspaceId: w.id }, { workspaceId: w.id, idempotencyKey: `seg:${w.id}:${Math.floor(Date.now() / 240000)}` });
  }
}

export async function daily() {
  const db = await getDb();
  const all = await db.select().from(schema.workspaces);
  const { detectAnomalies, checkPacing, trainScoringModel } = await import("./ai/features");
  const { runDateTriggers } = await import("./services/journeys");
  const { deliverScheduledReports } = await import("./services/reports");
  const { syncPostMetrics } = await import("./services/content");
  const { generateInvoice } = await import("./services/billing");
  const out: Record<string, unknown> = {};
  for (const w of all) {
    const ctx = await systemCtx(w.id);
    // ADS-002: daily sync of ad metrics (yesterday available by 08:00 workspace time)
    const ints = await db.select().from(schema.integrations).where(and(eq(schema.integrations.workspaceId, w.id), eq(schema.integrations.status, "connected")));
    for (const i of ints) await enqueue(db, "integration.sync", { workspaceId: w.id, integrationId: i.id }, { workspaceId: w.id, idempotencyKey: `sync:${i.id}:${new Date().toISOString().slice(0, 10)}` });
    for (const s of await db.select().from(schema.segments).where(eq(schema.segments.workspaceId, w.id))) {
      if (s.audienceSync.meta || s.audienceSync.google) await enqueue(db, "audience.sync", { workspaceId: w.id, segmentId: s.id }, { workspaceId: w.id, idempotencyKey: `aud:${s.id}:${new Date().toISOString().slice(0, 10)}` });
    }
    const safe = async (name: string, f: () => Promise<unknown>) => { try { out[`${w.slug}.${name}`] = await f(); } catch (e) { out[`${w.slug}.${name}`] = (e as Error).message; } };
    await safe("anomalies", async () => (await detectAnomalies(ctx)).length);
    await safe("pacing", async () => (await checkPacing(ctx)).length);
    await safe("dateTriggers", () => runDateTriggers(ctx));
    await safe("reports", () => deliverScheduledReports(ctx));
    await safe("postMetrics", () => syncPostMetrics(ctx));
    const social = await import("./services/social");
    const socialAccts = await import("./services/social-accounts");
    await safe("socialRollup", () => social.rollupMetrics(ctx));
    await safe("socialTokenHealth", () => socialAccts.tokenHealth(ctx));
    await safe("socialAdMap", () => socialAccts.syncAdMap(ctx));
    if (new Date().getUTCDay() === 1) await safe("scoring", () => trainScoringModel(ctx)); // AI-003 weekly retrain
    if (new Date().getUTCDate() === 1) {
      const prev = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth() - 1, 1)).toISOString().slice(0, 7);
      await safe("invoice", async () => (await generateInvoice(ctx, prev)).id);
    }
  }
  // retention: audit logs kept 1 year (ADM-003), idempotency keys 7 days, finished jobs 30 days
  const { lt, inArray } = await import("drizzle-orm");
  await db.delete(schema.auditLogs).where(lt(schema.auditLogs.at, new Date(Date.now() - 366 * 86400000)));
  await db.delete(schema.idempotencyKeys).where(lt(schema.idempotencyKeys.createdAt, new Date(Date.now() - 7 * 86400000)));
  await db.delete(schema.jobs).where(and(inArray(schema.jobs.status, ["done"]), lt(schema.jobs.updatedAt, new Date(Date.now() - 30 * 86400000))));
  await db.delete(schema.sessions).where(lt(schema.sessions.expiresAt, new Date()));
  return out;
}

export { isNull };
