import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import {
  canViewWeeklyKpiBoard,
  clearWeeklyKpisForDepartment,
  getWeeklyKpiBoard,
  upsertWeeklyDepartmentKpiRow,
  upsertWeeklyKpiFromPayload,
} from "@/lib/kpis/persistence";
import type { WeeklyKpiIngestPayload } from "@/lib/kpis/types";
import type { DepartmentKey } from "@/lib/types";

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

  const viewer = {
    role: session.user.role,
    department: session.user.department ?? null,
  };

  if (!canViewWeeklyKpiBoard(viewer)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const { searchParams } = new URL(request.url);
  const weekStart = searchParams.get("weekStart");

  const board = await getWeeklyKpiBoard({
    weekStartInput: weekStart,
    viewer,
  });

  return NextResponse.json(board);
}

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

  const viewer = {
    role: session.user.role,
    department: session.user.department ?? null,
  };

  if (!canViewWeeklyKpiBoard(viewer)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  if (session.user.role !== "owner") {
    return NextResponse.json({ error: "Only owner can modify core weekly KPI definitions." }, { status: 403 });
  }

  let payload: WeeklyKpiIngestPayload;
  try {
    payload = (await request.json()) as WeeklyKpiIngestPayload;
  } catch {
    return NextResponse.json({ error: "Invalid JSON body." }, { status: 400 });
  }

  if (!Array.isArray(payload.sections) || payload.sections.length === 0) {
    return NextResponse.json({ error: "At least one section is required." }, { status: 400 });
  }

  try {
    const board = await upsertWeeklyKpiFromPayload(payload);
    const scoped = await getWeeklyKpiBoard({
      weekStartInput: board.weekStart,
      viewer,
    });
    return NextResponse.json(scoped);
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Unable to ingest KPI payload." },
      { status: 400 }
    );
  }
}

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

  if (session.user.role !== "owner") {
    return NextResponse.json({ error: "Only owner can add grouped department KPIs." }, { status: 403 });
  }

  let payload:
    | {
        weekStart?: string;
        department?: DepartmentKey;
        groupTitle?: string;
        kpiName?: string;
        objectiveIndicator?: string | null;
        quantityQuality?: string | null;
        compliance?: string | null;
        dueCommitment?: string | null;
        ownerTeamLabel?: string | null;
      }
    | undefined;
  try {
    payload = (await request.json()) as typeof payload;
  } catch {
    return NextResponse.json({ error: "Invalid JSON body." }, { status: 400 });
  }

  if (!payload?.department || !payload.groupTitle || !payload.kpiName) {
    return NextResponse.json({ error: "department, groupTitle and kpiName are required." }, { status: 400 });
  }

  try {
    const board = await upsertWeeklyDepartmentKpiRow({
      weekStartInput: payload.weekStart,
      department: payload.department,
      groupTitle: payload.groupTitle,
      kpiName: payload.kpiName,
      objectiveIndicator: payload.objectiveIndicator,
      quantityQuality: payload.quantityQuality,
      compliance: payload.compliance,
      dueCommitment: payload.dueCommitment,
      ownerTeamLabel: payload.ownerTeamLabel,
    });

    const scoped = await getWeeklyKpiBoard({
      weekStartInput: board.weekStart,
      viewer: {
        role: session.user.role,
        department: session.user.department ?? null,
      },
    });

    return NextResponse.json({
      ok: true,
      board: scoped,
    });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Unable to create KPI row." },
      { status: 400 }
    );
  }
}

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

  if (session.user.role !== "owner") {
    return NextResponse.json({ error: "Only owner can clear department KPIs." }, { status: 403 });
  }

  const url = new URL(request.url);
  const department = url.searchParams.get("department") as DepartmentKey | null;
  const weekStart = url.searchParams.get("weekStart");
  if (!department) {
    return NextResponse.json({ error: "department query param is required." }, { status: 400 });
  }

  try {
    const result = await clearWeeklyKpisForDepartment({
      weekStartInput: weekStart,
      department,
    });
    const board = await getWeeklyKpiBoard({
      weekStartInput: result.weekStart,
      viewer: {
        role: session.user.role,
        department: session.user.department ?? null,
      },
    });

    return NextResponse.json({
      ok: true,
      result,
      board,
    });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Unable to clear department KPIs." },
      { status: 400 }
    );
  }
}
