import { NextResponse } from "next/server";
import { ApprovalState, DepartmentKey, PmWorkOrderState, ProductionPlanState } from "@prisma/client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

type PatchApprovalBody = {
  action?: "approve" | "reject";
};

export async function PATCH(request: Request, context: { params: { id: string } }) {
  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 approve/reject requests." }, { status: 403 });
  }

  const body = (await request.json().catch(() => ({}))) as PatchApprovalBody;
  if (body.action !== "approve" && body.action !== "reject") {
    return NextResponse.json({ error: "action must be approve or reject." }, { status: 400 });
  }

  const approval = await prisma.approvalRequest.findFirst({
    where: {
      id: context.params.id,
      department: DepartmentKey.operaciones,
    },
  });
  if (!approval) {
    return NextResponse.json({ error: "Approval request not found." }, { status: 404 });
  }
  if (approval.state !== ApprovalState.pending_owner && approval.state !== ApprovalState.submitted) {
    return NextResponse.json({ error: "Approval request is not pending." }, { status: 400 });
  }

  const approved = body.action === "approve";
  const decidedAt = new Date();

  await prisma.$transaction(async (tx) => {
    await tx.approvalRequest.update({
      where: { id: approval.id },
      data: {
        state: approved ? ApprovalState.approved : ApprovalState.rejected,
        approverId: session.user.id,
        decidedAt,
      },
    });

    if (approval.workOrderId) {
      await tx.pmWorkOrder.update({
        where: { id: approval.workOrderId },
        data: {
          state: approved ? PmWorkOrderState.scheduled : PmWorkOrderState.cancelled,
          approvedById: approved ? session.user.id : null,
        },
      });
    }

    if (approval.productionPlanId) {
      await tx.productionPlan.update({
        where: { id: approval.productionPlanId },
        data: {
          state: approved ? ProductionPlanState.approved : ProductionPlanState.replanned,
          approvedById: approved ? session.user.id : null,
          approvedAt: approved ? decidedAt : null,
        },
      });
    }
  });

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