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 { canAccessOperations, canManageOperations, ensureDefaultMaintenancePolicy, resolveOwnerUserId } from "@/lib/operations";

type UpdatePolicyBody = {
  costThreshold?: number;
  downtimeThresholdHours?: number;
  ownerUserId?: string | null;
};

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

  await ensureDefaultMaintenancePolicy(session.user.role === "owner" ? session.user.id : await resolveOwnerUserId());
  const policy = await prisma.maintenanceApprovalPolicy.findUnique({
    where: {
      department: DepartmentKey.operaciones,
    },
  });

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

export async function PATCH(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 update policy." }, { status: 403 });
  }

  await ensureDefaultMaintenancePolicy(session.user.role === "owner" ? session.user.id : await resolveOwnerUserId());
  const policy = await prisma.maintenanceApprovalPolicy.findUnique({
    where: {
      department: DepartmentKey.operaciones,
    },
    select: { id: true, ownerUserId: true },
  });
  if (!policy) {
    return NextResponse.json({ error: "Policy not found." }, { status: 404 });
  }

  const body = (await request.json().catch(() => ({}))) as UpdatePolicyBody;
  const nextCostThreshold = body.costThreshold !== undefined ? Math.max(0, body.costThreshold) : undefined;
  const nextDowntimeThreshold =
    body.downtimeThresholdHours !== undefined ? Math.max(0, body.downtimeThresholdHours) : undefined;
  const nextOwnerUserId =
    body.ownerUserId !== undefined ? (body.ownerUserId?.trim() ? body.ownerUserId.trim() : null) : undefined;

  const updated = await prisma.maintenanceApprovalPolicy.update({
    where: {
      id: policy.id,
    },
    data: {
      ...(nextCostThreshold !== undefined ? { costThreshold: nextCostThreshold } : {}),
      ...(nextDowntimeThreshold !== undefined ? { downtimeThresholdHours: nextDowntimeThreshold } : {}),
      ...(nextOwnerUserId !== undefined ? { ownerUserId: nextOwnerUserId } : {}),
    },
  });

  return NextResponse.json({ ok: true, policy: updated });
}
