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, mapBrandPulse } from "@/lib/marketing/persistence";

type UpdateBrandPulseBody = {
  rating1to5?: number;
  notes?: string;
};

function currentMonthIso(): string {
  return new Date().toISOString().slice(0, 7);
}

export async function PATCH(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 owners or marketing leaders can update Brand Pulse." }, { status: 403 });
  }

  const body = (await request.json()) as UpdateBrandPulseBody;
  const ratingRaw = Number(body.rating1to5);
  const notes = body.notes?.trim() ?? "";

  if (!Number.isFinite(ratingRaw)) {
    return NextResponse.json({ error: "Invalid rating1to5." }, { status: 400 });
  }

  const rating1to5 = Math.min(5, Math.max(1, Math.round(ratingRaw)));

  const brandPulse = await prisma.marketingBrandPulse.create({
    data: {
      department: DepartmentKey.marketing,
      month: currentMonthIso(),
      rating1to5,
      notes,
      updatedById: session.user.id,
      updatedByName: session.user.name ?? session.user.email,
    },
  });

  return NextResponse.json({
    ok: true,
    brandPulse: mapBrandPulse(brandPulse),
  });
}
