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

type PatchWorkOrderBody = {
  state?: PmWorkOrderState;
  actualCost?: number | null;
  actualDowntimeHours?: number | null;
  startedAt?: string | null;
  completedAt?: string | null;
  approvalAction?: "approve" | "reject";
};

const VALID_STATES = new Set<PmWorkOrderState>([
  PmWorkOrderState.draft,
  PmWorkOrderState.scheduled,
  PmWorkOrderState.in_progress,
  PmWorkOrderState.completed,
  PmWorkOrderState.verified,
  PmWorkOrderState.overdue,
  PmWorkOrderState.cancelled,
]);

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 (!canManageOperations(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owner/operations leader can update work orders." }, { status: 403 });
  }

  const body = (await request.json()) as PatchWorkOrderBody;
  const startedAt = body.startedAt ? new Date(body.startedAt) : null;
  const completedAt = body.completedAt ? new Date(body.completedAt) : null;

  const existing = await prisma.pmWorkOrder.findFirst({
    where: {
      id: context.params.id,
      asset: {
        department: DepartmentKey.operaciones,
      },
    },
    include: {
      approvalRequests: {
        where: {
          state: {
            in: [ApprovalState.pending_owner, ApprovalState.submitted],
          },
        },
        orderBy: { createdAt: "desc" },
        take: 1,
      },
    },
  });

  if (!existing) {
    return NextResponse.json({ error: "Work order not found in operations department." }, { status: 404 });
  }

  const pendingApproval = existing.approvalRequests[0] ?? null;
  if (body.approvalAction) {
    if (session.user.role !== "owner") {
      return NextResponse.json({ error: "Only owner can approve/reject work orders." }, { status: 403 });
    }
    if (!pendingApproval) {
      return NextResponse.json({ error: "No pending approval request found for this work order." }, { status: 400 });
    }
    const approved = body.approvalAction === "approve";

    await prisma.approvalRequest.update({
      where: { id: pendingApproval.id },
      data: {
        state: approved ? ApprovalState.approved : ApprovalState.rejected,
        approverId: session.user.id,
        decidedAt: new Date(),
      },
    });

    await prisma.pmWorkOrder.update({
      where: { id: context.params.id },
      data: {
        state: approved ? PmWorkOrderState.scheduled : PmWorkOrderState.cancelled,
        approvedById: approved ? session.user.id : null,
      },
    });

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

  if (body.state && pendingApproval && session.user.role !== "owner") {
    return NextResponse.json(
      { error: "This work order requires owner approval before state transitions." },
      { status: 403 }
    );
  }

  await prisma.pmWorkOrder.update({
    where: { id: context.params.id },
    data: {
      ...(body.state && VALID_STATES.has(body.state) ? { state: body.state } : {}),
      ...(body.actualCost !== undefined ? { actualCost: body.actualCost === null ? null : Math.max(0, body.actualCost) } : {}),
      ...(body.actualDowntimeHours !== undefined
        ? { actualDowntimeHours: body.actualDowntimeHours === null ? null : Math.max(0, body.actualDowntimeHours) }
        : {}),
      ...(body.startedAt !== undefined ? { startedAt: startedAt && !Number.isNaN(startedAt.getTime()) ? startedAt : null } : {}),
      ...(body.completedAt !== undefined
        ? { completedAt: completedAt && !Number.isNaN(completedAt.getTime()) ? completedAt : null }
        : {}),
    },
  });

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