/** Omnichannel messaging & unified inbox (MSG-001…007, FLOW-007, NFR-011). */
import { and, desc, eq, gte, inArray, sql } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { emit } from "@/lib/webhooks";
import { audit } from "@/lib/audit";
import { ApiError } from "@/lib/api";
import { findIntegrations, MESSAGING_PROVIDERS, pushVia } from "@/connectors";
import { fullName, localMinutes, normalizeEmail, renderTemplate, randomToken } from "@/lib/util";
import { canMessage, getContact, setConsent, upsertContact, type Contact } from "./contacts";
import { recordUsage } from "./billing";
import { notifyUser } from "./notify";

export const CHANNEL_LABEL: Record<string, string> = { whatsapp: "WhatsApp", email: "Email", sms: "SMS", messenger: "Messenger", instagram: "Instagram", push: "Push" };
const OPT_OUT = /^\s*(stop|unsubscribe|cancel|end|quit|optout|opt out|বন্ধ|বাতিল)\s*$/i;

export async function getOrCreateConversation(ctx: Pick<Ctx, "db" | "workspace">, contact: Contact, channel: string, initialStatus = "open") {
  const ex = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.workspaceId, ctx.workspace.id), eq(schema.conversations.contactId, contact.id), eq(schema.conversations.channel, channel)) });
  if (ex) return ex;
  const [c] = await ctx.db.insert(schema.conversations).values({ workspaceId: ctx.workspace.id, contactId: contact.id, channel, assigneeId: contact.ownerId, status: initialStatus }).returning();
  return c!;
}

/** Variables available in templates: {{first_name|there}}, {{last_name}}, {{name}}, {{phone}}, {{email}}, {{city}}, {{project}}, {{owner_name}}, {{custom.budget}}, {{workspace}} */
export async function templateVars(ctx: Pick<Ctx, "db" | "workspace">, contact: Contact) {
  const owner = contact.ownerId ? await ctx.db.query.users.findFirst({ where: eq(schema.users.id, contact.ownerId) }) : null;
  return { first_name: contact.firstName, last_name: contact.lastName, name: fullName(contact), phone: contact.phones[0], email: contact.emails[0], city: contact.city, project: contact.project, owner_name: owner?.name, custom: contact.customFields, workspace: ctx.workspace.name };
}

/** FLOW-007: is `at` inside the workspace's quiet hours? Returns the next allowed time if so. */
export function quietHoursDelay(ws: Ctx["workspace"], at = new Date()): Date | null {
  const q = ws.settings?.quietHours;
  if (!q?.enabled) return null;
  const toMin = (s: string) => Number(s.split(":")[0]) * 60 + Number(s.split(":")[1] ?? 0);
  const start = toMin(q.start), end = toMin(q.end), now = localMinutes(at, ws.timezone);
  const inQuiet = start > end ? now >= start || now < end : now >= start && now < end;
  if (!inQuiet) return null;
  const wait = (end - now + 1440) % 1440;
  return new Date(at.getTime() + wait * 60000);
}

export type SendInput = {
  contactId: string; channel: string; body?: string; subject?: string; templateId?: string | null; mediaUrl?: string;
  source: "human" | "journey" | "broadcast" | "ai" | "api"; broadcastId?: string; conversationId?: string;
};

export async function sendMessage(ctx: Ctx, input: SendInput): Promise<{ message: typeof schema.messages.$inferSelect | null; deferredUntil?: Date; blocked?: string }> {
  const contact = await getContact(ctx, input.contactId);
  if (ctx.perms.messaging === "C:assigned" && contact.ownerId !== ctx.user?.id) throw new ApiError(403, "forbidden", "You can only message your assigned contacts");
  const channel = input.channel;
  if (!MESSAGING_PROVIDERS[channel]) throw new ApiError(422, "validation_failed", `Unsupported channel ${channel}`);
  const automated = input.source !== "human";

  if (automated) {
    const delay = quietHoursDelay(ctx.workspace);
    if (delay) return { message: null, deferredUntil: delay };
    const cap = ctx.workspace.settings?.frequencyCap;
    if (cap?.enabled && cap.perDay > 0) {
      const [{ n }] = await ctx.db.select({ n: sql<number>`count(*)::int` }).from(schema.messages).innerJoin(schema.conversations, eq(schema.conversations.id, schema.messages.conversationId))
        .where(and(eq(schema.conversations.contactId, contact.id), eq(schema.messages.direction, "out"), gte(schema.messages.createdAt, new Date(Date.now() - 86400000)), sql`${schema.messages.senderId} IS NULL`)) as [{ n: number }];
      if (n >= cap.perDay) return { message: null, blocked: `Frequency cap of ${cap.perDay}/day reached` };
    }
  }

  const template = input.templateId ? await ctx.db.query.templates.findFirst({ where: and(eq(schema.templates.id, input.templateId), eq(schema.templates.workspaceId, ctx.workspace.id)) }) : null;
  const vars = await templateVars(ctx, contact);
  const body = renderTemplate(template?.body ?? input.body ?? "", vars).trim();
  const subject = input.subject || template?.subject ? renderTemplate(input.subject ?? template?.subject ?? "", vars) : null;
  if (!body && !input.mediaUrl) throw new ApiError(422, "validation_failed", "Message body is empty");

  const conv = input.conversationId
    ? (await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, input.conversationId), eq(schema.conversations.workspaceId, ctx.workspace.id)) }))!
    : await getOrCreateConversation(ctx, contact, channel, input.source === "human" ? "pending" : "closed");
  const [msg] = await ctx.db.insert(schema.messages).values({
    workspaceId: ctx.workspace.id, conversationId: conv.id, direction: "out", channel, templateId: template?.id ?? null, subject, body,
    media: input.mediaUrl ? [{ url: input.mediaUrl, type: "image" }] : [], senderId: input.source === "human" ? ctx.user?.id ?? null : null, broadcastId: input.broadcastId ?? null, status: "queued",
  }).returning();

  const fail = async (status: "blocked" | "failed", error: string) => {
    const [m] = await ctx.db.update(schema.messages).set({ status, error }).where(eq(schema.messages.id, msg!.id)).returning();
    return { message: m!, blocked: status === "blocked" ? error : undefined };
  };

  // consent (CDP-004): opted-out contacts are excluded from all sends
  const consent = await canMessage(ctx, contact, channel);
  if (!consent.ok) return fail("blocked", consent.reason!);

  // recipient address
  const to = channel === "email" ? contact.emails[0] : channel === "messenger" || channel === "instagram" ? contact.socialIds?.messenger : contact.phones[0];
  if (!to) return fail("failed", `Contact has no ${channel === "email" ? "email address" : channel === "messenger" ? "Messenger ID" : "phone number"}`);

  // WhatsApp 24-hour customer-service window: outside it only approved templates may be sent (NFR-011)
  let waTemplate: string | undefined;
  if (channel === "whatsapp") {
    const lastIn = await ctx.db.select({ at: schema.messages.createdAt }).from(schema.messages).where(and(eq(schema.messages.conversationId, conv.id), eq(schema.messages.direction, "in"))).orderBy(desc(schema.messages.createdAt)).limit(1);
    const inWindow = lastIn[0] && Date.now() - lastIn[0].at.getTime() < 24 * 3600000;
    if (!inWindow) {
      if (!template) return fail("blocked", "Outside the 24h WhatsApp window — choose an approved template");
      if (template.providerStatus !== "approved") return fail("blocked", `Template "${template.name}" is not approved by WhatsApp yet`);
      waTemplate = template.name;
    }
  }

  const integrations = await findIntegrations(ctx, MESSAGING_PROVIDERS[channel]!);
  if (!integrations.length) return fail("failed", `No ${CHANNEL_LABEL[channel]} provider connected — connect one in Integrations`);

  let lastErr = "";
  for (const integration of integrations) {
    try {
      const payload: Record<string, unknown> = { to, body, subject, messageId: msg!.id, mediaUrl: input.mediaUrl, psid: to };
      if (waTemplate) {
        payload.template = waTemplate.toLowerCase().replace(/[^a-z0-9_]/g, "_");
        payload.language = template?.language ?? "en";
        const params = (template?.variables ?? []).map((v) => ({ type: "text", text: String(renderTemplate(`{{${v}|-}}`, vars)) }));
        payload.components = params.length ? [{ type: "body", parameters: params }] : [];
      }
      if (channel === "email") payload.html = await emailHtml(ctx, msg!.id, contact, body);
      const op = channel === "messenger" || channel === "instagram" ? "messenger.send" : "send";
      const r = await pushVia(ctx, integration, op, payload);
      const [m] = await ctx.db.update(schema.messages).set({ status: "sent", providerMessageId: String(r.providerMessageId ?? ""), error: null, updatedAt: new Date() }).where(eq(schema.messages.id, msg!.id)).returning();
      // Module 11: a reply to an inbound message counts as the first response (SLA cleared; human/ai/rule tracked for automation reports)
      const replying = !!conv.lastInboundAt && !conv.firstResponseAt && ["human", "ai", "journey"].includes(input.source ?? "");
      await ctx.db.update(schema.conversations).set({
        lastMessageAt: new Date(), status: input.source === "human" ? "pending" : conv.status, updatedAt: new Date(),
        ...(replying ? { firstResponseAt: new Date(), slaDueAt: null, handledBy: input.source === "human" ? "human" : input.source === "ai" ? "ai" : "rule" } : {}),
      }).where(eq(schema.conversations.id, conv.id));
      await ctx.db.update(schema.contacts).set({ lastActivityAt: new Date(), ...(input.source === "human" ? { firstContactedAt: sql`COALESCE(${schema.contacts.firstContactedAt}, now())` } : {}) }).where(eq(schema.contacts.id, contact.id));
      const meter = channel === "sms" ? "sms" : channel === "whatsapp" ? "whatsapp" : channel === "email" ? "email" : null;
      if (meter) await recordUsage(ctx, meter, Number(r.segments ?? 1));
      if (input.source === "human") await audit(ctx, "send", "message", m!.id, undefined, { channel, to: contact.id });
      return { message: m! };
    } catch (e) {
      lastErr = e instanceof Error ? e.message : String(e);
      // failover to next provider (local SMS → Twilio, SES → SendGrid)
    }
  }
  return fail("failed", lastErr);
}

async function emailHtml(ctx: Pick<Ctx, "db" | "workspace">, messageId: string, contact: Contact, body: string) {
  const base = process.env.APP_URL ?? "http://localhost:3000";
  const token = Buffer.from(`${ctx.workspace.id}:${contact.id}`).toString("base64url");
  const html = body.includes("<") ? body : body.split(/\n{2,}/).map((p) => `<p>${p.replace(/\n/g, "<br/>")}</p>`).join("");
  const tracked = html.replace(/href="(https?:\/\/[^"]+)"/g, (_m, url) => `href="${base}/api/track/click/${messageId}?u=${encodeURIComponent(url)}"`);
  return `<!doctype html><html><body style="font-family:Arial,sans-serif;font-size:15px;line-height:1.6;color:#111;max-width:600px;margin:auto;padding:24px">${tracked}<hr style="border:none;border-top:1px solid #eee;margin:32px 0 12px"/><p style="font-size:12px;color:#888">${ctx.workspace.name} · <a href="${base}/u/${token}" style="color:#888">Unsubscribe</a></p><img src="${base}/api/track/open/${messageId}" width="1" height="1" alt="" style="display:none"/></body></html>`;
}

export async function receiveMessage(ctx: Ctx, m: { channel: string; from: string; name?: string; body: string; providerMessageId?: string; waId?: string; psid?: string }) {
  if (m.providerMessageId) {
    const dup = await ctx.db.query.messages.findFirst({ where: and(eq(schema.messages.workspaceId, ctx.workspace.id), eq(schema.messages.providerMessageId, m.providerMessageId)) });
    if (dup) return dup;
  }
  const email = m.channel === "email" ? normalizeEmail(m.from) : null;
  const { contact, created } = await upsertContact(ctx, {
    name: m.name, email, phone: ["whatsapp", "sms"].includes(m.channel) ? m.from : null, waId: m.waId ?? null, psid: m.psid ?? null, source: m.channel,
  }, { source: m.channel });
  const conv = await getOrCreateConversation(ctx, contact, m.channel);
  const [msg] = await ctx.db.insert(schema.messages).values({ workspaceId: ctx.workspace.id, conversationId: conv.id, direction: "in", channel: m.channel, body: m.body, status: "received", providerMessageId: m.providerMessageId ?? null }).returning();
  await ctx.db.update(schema.conversations).set({ lastMessageAt: new Date(), unread: sql`${schema.conversations.unread} + 1`, status: "open", updatedAt: new Date() }).where(eq(schema.conversations.id, conv.id));
  await ctx.db.update(schema.contacts).set({ lastActivityAt: new Date() }).where(eq(schema.contacts.id, contact.id));

  // NFR-011: honour opt-outs immediately
  if (OPT_OUT.test(m.body)) await setConsent(ctx, contact.id, m.channel === "instagram" ? "messenger" : m.channel, "opted_out", `${m.channel} keyword`);
  else if (/^\s*(start|subscribe|yes)\s*$/i.test(m.body)) await setConsent(ctx, contact.id, m.channel === "instagram" ? "messenger" : m.channel, "opted_in", `${m.channel} keyword`);

  await emit(ctx.db, ctx.workspace.id, "message.received", { message_id: msg!.id, conversation_id: conv.id, contact_id: contact.id, channel: m.channel, body: m.body });
  // Module 11: windows, SLA, classification, engagement rules & routing for DMs
  try {
    const { onInboundDm } = await import("./social");
    await onInboundDm(ctx, conv.id, contact.id, m.body, created);
  } catch (e) { console.error("[social.dm]", e); }
  if (created && ["whatsapp", "messenger", "instagram"].includes(m.channel)) {
    const { captureLead } = await import("./leads");
    await captureLead(ctx, { phone: m.from, waId: m.waId, psid: m.psid, name: m.name, attribution: { channel: m.channel } });
  } else if (conv.assigneeId ?? contact.ownerId) {
    await notifyUser(ctx, (conv.assigneeId ?? contact.ownerId)!, "message", `${CHANNEL_LABEL[m.channel]} from ${fullName(contact)}`, m.body.slice(0, 140), `/inbox?c=${conv.id}`);
  }
  const { triggerJourneys, checkGoals } = await import("./journeys");
  await triggerJourneys(ctx, "event_received", contact.id, { event: "message_received", channel: m.channel });
  await checkGoals(ctx, contact.id, "event_received", "message_received");
  // AI-002 qualification agent
  const fresh = await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, conv.id) });
  if (fresh?.aiAgentActive || (created && process.env.AI_AGENT_AUTO_START === "true")) {
    const { enqueue } = await import("@/lib/jobs");
    await enqueue(ctx.db, "ai.agent_reply", { workspaceId: ctx.workspace.id, conversationId: conv.id }, { workspaceId: ctx.workspace.id });
  }
  return msg!;
}

export async function updateMessageStatus(ctx: Ctx, providerMessageId: string, status: string, error?: string) {
  if (!providerMessageId) return;
  const order = ["queued", "sent", "delivered", "read", "clicked"];
  const m = await ctx.db.query.messages.findFirst({ where: and(eq(schema.messages.workspaceId, ctx.workspace.id), eq(schema.messages.providerMessageId, providerMessageId)) });
  if (!m) return;
  const norm = status === "clicked" ? "read" : status;
  if (norm !== "failed" && order.indexOf(norm) <= order.indexOf(m.status)) return;
  await ctx.db.update(schema.messages).set({
    status: norm, error: error ?? m.error, updatedAt: new Date(),
    ...(status === "read" && !m.openedAt ? { openedAt: new Date() } : {}), ...(status === "clicked" ? { clickedAt: new Date() } : {}),
  }).where(eq(schema.messages.id, m.id));
  await emit(ctx.db, ctx.workspace.id, "message.status_changed", { message_id: m.id, status: norm, error: error ?? null });
}

/** MSG-002: hard bounces suppress the address automatically */
export async function handleBounce(ctx: Ctx, email: string, type: "hard" | "soft" | "complaint") {
  if (type === "soft") return;
  const e = normalizeEmail(email);
  if (!e) return;
  const id = await ctx.db.query.identities.findFirst({ where: and(eq(schema.identities.workspaceId, ctx.workspace.id), eq(schema.identities.type, "email"), eq(schema.identities.valueNormalized, e)) });
  if (id) await setConsent(ctx, id.contactId, "email", "opted_out", type === "complaint" ? "spam complaint" : "hard bounce");
}

/* ---------------- Broadcasts (MSG-006) ---------------- */

export async function processBroadcast(ctx: Ctx, broadcastId: string) {
  const b = await ctx.db.query.broadcasts.findFirst({ where: eq(schema.broadcasts.id, broadcastId) });
  if (!b || !["scheduled", "sending"].includes(b.status)) return { done: true };
  if (b.scheduledAt && b.scheduledAt > new Date()) return { done: false, runAt: b.scheduledAt };
  const delay = quietHoursDelay(ctx.workspace);
  if (delay) return { done: false, runAt: delay };
  const { segmentMemberIds } = await import("./segments");
  const ids = b.segmentId ? await segmentMemberIds(ctx, b.segmentId) : [];
  const batch = ids.slice(b.cursor, b.cursor + b.throttlePerMinute);
  const stats = { targeted: ids.length, sent: b.stats.sent ?? 0, skipped: b.stats.skipped ?? 0, failed: b.stats.failed ?? 0 };
  for (const contactId of batch) {
    try {
      const r = await sendMessage(ctx, { contactId, channel: b.channel, body: b.body ?? undefined, subject: b.subject ?? undefined, templateId: b.templateId, source: "broadcast", broadcastId: b.id });
      if (r.message?.status === "sent") stats.sent++;
      else if (r.message?.status === "failed") stats.failed++;
      else stats.skipped++;
    } catch {
      stats.failed++;
    }
  }
  const cursor = b.cursor + batch.length;
  const done = cursor >= ids.length;
  await ctx.db.update(schema.broadcasts).set({ cursor, stats, status: done ? "sent" : "sending", updatedAt: new Date() }).where(eq(schema.broadcasts.id, b.id));
  return { done, runAt: new Date(Date.now() + 60000) };
}

export async function inboxCounts(ctx: Ctx) {
  const rows = await ctx.db.select({ status: schema.conversations.status, n: sql<number>`count(*)::int` }).from(schema.conversations).where(eq(schema.conversations.workspaceId, ctx.workspace.id)).groupBy(schema.conversations.status);
  return Object.fromEntries(rows.map((r) => [r.status, r.n]));
}

export const unsubscribeToken = randomToken;
export { inArray };
