import { NextResponse } from "next/server";
import { DepartmentKey } from "@prisma/client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { canManageMarketing } from "@/lib/marketing/persistence";
import { buildInsightsFromSnapshots } from "@/lib/marketing/meta";
import { mapSocialSnapshot } from "@/lib/marketing/persistence";
import { publishMarketingKpis } from "@/lib/kpis/publishers";
import { getWeekBounds } from "@/lib/kpis/date";
import {
  completeCaptureAutomationRunFailure,
  completeCaptureAutomationRunSuccess,
  startCaptureAutomationRun,
} from "@/lib/capture";

export async function POST(request: Request) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canManageMarketing(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owner/marketing leader can publish KPIs." }, { status: 403 });
  }

  const { searchParams } = new URL(request.url);
  const requestedWeekStart = searchParams.get("weekStart") ?? undefined;
  const { weekStart } = getWeekBounds(requestedWeekStart);
  const run = await startCaptureAutomationRun({
    department: DepartmentKey.marketing,
    weekStart,
    source: "marketing-kpi-publish-v1",
    triggeredById: session.user.id,
  });

  const [snapshotsRaw, activeInitiatives] = await Promise.all([
    prisma.marketingSocialSnapshot.findMany({
      where: { department: DepartmentKey.marketing },
      orderBy: { capturedAt: "desc" },
      take: 20,
    }),
    prisma.marketingInitiative.count({
      where: {
        department: DepartmentKey.marketing,
        status: { in: ["planning", "in_progress", "completion"] },
      },
    }),
  ]);

  const insights = buildInsightsFromSnapshots(snapshotsRaw.map(mapSocialSnapshot));
  const sevenDay = insights.filter((item) => item.range === "7d");
  const growthPct7d = sevenDay.length > 0 ? sevenDay.reduce((acc, item) => acc + item.followerGrowthPct, 0) / sevenDay.length : 0;
  const engagementPct7d =
    sevenDay.length > 0 ? sevenDay.reduce((acc, item) => acc + item.engagementRatePct, 0) / sevenDay.length : 0;
  const instagram7d = sevenDay.find((item) => item.channel === "instagram");
  const instagramReach7d = instagram7d?.reach ?? 0;
  const instagramFollowers = instagram7d?.followersEnd ?? 0;

  try {
    const publishResult = await publishMarketingKpis({
      growthPct7d,
      engagementPct7d,
      activeInitiatives,
      syncStatus: "ready",
      instagramReach7d,
      instagramFollowers,
      weekStart: requestedWeekStart,
    });

    await completeCaptureAutomationRunSuccess({
      runId: run.id,
      department: DepartmentKey.marketing,
      weekStart: publishResult.weekStart,
      source: run.source,
      sectionKey: publishResult.sectionKey,
      rowsTouched: publishResult.rowCount,
    });

    return NextResponse.json({ ok: true, publishResult });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Failed to publish marketing KPIs.";
    await completeCaptureAutomationRunFailure({
      runId: run.id,
      message,
    });
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
