/** Content & social (CNT-001…005): calendar, scheduling/auto-publishing, approvals with client links, metrics sync. */
import { and, eq, lte } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { audit } from "@/lib/audit";
import { ApiError } from "@/lib/api";
import { randomToken } from "@/lib/util";
import { findIntegration, pushVia } from "@/connectors";

export const SOCIAL_CHANNELS = [
  { key: "facebook", label: "Facebook", provider: "meta" }, { key: "instagram", label: "Instagram", provider: "meta" },
  { key: "linkedin", label: "LinkedIn", provider: "linkedin" }, { key: "tiktok", label: "TikTok", provider: "tiktok" },
];

export const POST_FLOW: Record<string, string[]> = {
  draft: ["in_review"], in_review: ["approved", "draft"], approved: ["scheduled", "draft"], scheduled: ["draft", "published"], published: [], failed: ["draft", "scheduled"],
};

export async function transitionPost(ctx: Ctx, id: string, to: string, note?: string) {
  const p = await ctx.db.query.contentPosts.findFirst({ where: and(eq(schema.contentPosts.id, id), eq(schema.contentPosts.workspaceId, ctx.workspace.id)) });
  if (!p) throw new ApiError(404, "not_found", "Post not found");
  if (!POST_FLOW[p.status]?.includes(to)) throw new ApiError(422, "invalid_transition", `Cannot move a ${p.status.replace("_", " ")} post to ${to.replace("_", " ")}`);
  if (to === "approved" && !["A", "C"].includes(ctx.perms.content)) throw new ApiError(403, "forbidden", "You cannot approve content");
  if (to === "approved" && ctx.perms.content === "C" && !["agency_admin", "workspace_admin"].includes(ctx.roleKey)) throw new ApiError(403, "forbidden", "Content creators cannot approve their own posts — a manager or client approves");
  if (to === "scheduled" && !p.scheduledAt) throw new ApiError(422, "validation_failed", "Set a publish date before scheduling");
  const patch: Partial<typeof p> = { status: to, updatedAt: new Date() };
  if (to === "in_review") patch.approvalToken = p.approvalToken ?? randomToken(18);
  if (to === "approved") { patch.approverId = ctx.user?.id ?? null; patch.approvalNote = note ?? null; }
  if (to === "draft" && note) patch.approvalNote = note;
  const [r] = await ctx.db.update(schema.contentPosts).set(patch).where(eq(schema.contentPosts.id, id)).returning();
  await audit(ctx, `content.${to}`, "content_post", id, { status: p.status }, { status: to, note });
  if (to === "in_review") {
    const { notifyAdmins } = await import("./notify");
    await notifyAdmins(ctx, "approval", "Post ready for review", p.body.slice(0, 120), `/content?post=${id}`, ["marketing_manager", "workspace_admin", "client_viewer"]);
  }
  return r!;
}

/** CNT-003: a client approves from a link without a full login. */
export async function approveByToken(ctx: Ctx, token: string, decision: "approve" | "changes", note?: string) {
  const p = await ctx.db.query.contentPosts.findFirst({ where: and(eq(schema.contentPosts.approvalToken, token), eq(schema.contentPosts.workspaceId, ctx.workspace.id)) });
  if (!p || p.status !== "in_review") throw new ApiError(404, "not_found", "This approval link is no longer active");
  const [r] = await ctx.db.update(schema.contentPosts).set({ status: decision === "approve" ? "approved" : "draft", approvalNote: note ?? null, updatedAt: new Date() }).where(eq(schema.contentPosts.id, p.id)).returning();
  await audit({ ...ctx, actor: { type: "user", id: null, name: "Client (approval link)" } }, decision === "approve" ? "content.approved" : "content.changes_requested", "content_post", p.id, { status: p.status }, { status: r!.status, note });
  return r!;
}

/** CNT-002: publish due posts and log external post IDs. */
export async function publishDuePosts(ctx: Ctx) {
  const due = await ctx.db.select().from(schema.contentPosts).where(and(eq(schema.contentPosts.workspaceId, ctx.workspace.id), eq(schema.contentPosts.status, "scheduled"), lte(schema.contentPosts.scheduledAt, new Date())));
  for (const p of due) {
    const ids: Record<string, string> = { ...p.externalPostIds };
    const errors: string[] = [];
    for (const ch of p.channels) {
      if (ids[ch]) continue;
      const provider = SOCIAL_CHANNELS.find((c) => c.key === ch)?.provider ?? ch;
      const integ = await findIntegration(ctx, provider === "meta" ? "meta" : provider);
      if (!integ) { errors.push(`${ch}: not connected`); continue; }
      try {
        const r = await pushVia(ctx, integ, "publish", { channel: ch, body: p.body, media: p.media });
        ids[ch] = String(r.postId);
      } catch (e) {
        errors.push(`${ch}: ${(e as Error).message}`);
      }
    }
    const allDone = p.channels.every((c) => ids[c]);
    await ctx.db.update(schema.contentPosts).set({ externalPostIds: ids, status: allDone ? "published" : "failed", publishedAt: allDone ? new Date() : null, approvalNote: errors.length ? errors.join("; ") : p.approvalNote, updatedAt: new Date() }).where(eq(schema.contentPosts.id, p.id));
    await audit(ctx, allDone ? "content.published" : "content.publish_failed", "content_post", p.id, undefined, { ids, errors });
  }
  return due.length;
}

/** CNT-005: post performance sync. */
export async function syncPostMetrics(ctx: Ctx) {
  const posts = await ctx.db.select().from(schema.contentPosts).where(and(eq(schema.contentPosts.workspaceId, ctx.workspace.id), eq(schema.contentPosts.status, "published")));
  for (const p of posts) {
    const totals = { reach: 0, engagement: 0, likes: 0, comments: 0, shares: 0 };
    for (const [ch, postId] of Object.entries(p.externalPostIds)) {
      const provider = SOCIAL_CHANNELS.find((c) => c.key === ch)?.provider ?? ch;
      const integ = await findIntegration(ctx, provider);
      if (!integ) continue;
      try {
        const m = await pushVia(ctx, integ, "post_metrics", { postId, channel: ch });
        for (const k of Object.keys(totals) as (keyof typeof totals)[]) totals[k] += Number(m[k] ?? 0);
      } catch { /* keep previous metrics */ }
    }
    await ctx.db.update(schema.contentPosts).set({ metrics: totals }).where(eq(schema.contentPosts.id, p.id));
  }
  return posts.length;
}
