import { NextResponse } from "next/server";
import { DepartmentKey } from "@prisma/client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { canManageOperations, getOperationsDashboardData } from "@/lib/operations";
import { publishOperationsKpis } 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 (!canManageOperations(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owner/operations 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.operaciones,
    weekStart,
    source: "operations-kpi-publish-v1",
    triggeredById: session.user.id,
  });

  try {
    const dashboard = await getOperationsDashboardData();
    const publishResult = await publishOperationsKpis({
      overdueWorkOrders: dashboard.summary.overdueWorkOrders,
      pendingApprovals: dashboard.summary.pendingApprovals,
      plannedUnits: dashboard.summary.plannedUnits,
      forecastUnits: dashboard.summary.forecastUnits,
      weekStart: requestedWeekStart,
    });

    await completeCaptureAutomationRunSuccess({
      runId: run.id,
      department: DepartmentKey.operaciones,
      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 operations KPIs.";
    await completeCaptureAutomationRunFailure({
      runId: run.id,
      message,
    });
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
