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

type PatchPlanBody = {
  lineName?: string;
  plannedUnits?: number;
  forecastUnits?: number;
  capacityUnits?: number;
  state?: ProductionPlanState;
  approvalAction?: "approve" | "reject";
};

const VALID_STATES = new Set<ProductionPlanState>([
  ProductionPlanState.draft,
  ProductionPlanState.simulated,
  ProductionPlanState.locked,
  ProductionPlanState.approved,
  ProductionPlanState.released,
  ProductionPlanState.replanned,
]);
const OWNER_ONLY_STATES = new Set<ProductionPlanState>([ProductionPlanState.approved, ProductionPlanState.released]);

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 production plans." }, { status: 403 });
  }

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

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

  const plannedUnits = body.plannedUnits ?? existing.plannedUnits;
  const forecastUnits = body.forecastUnits ?? existing.forecastUnits;
  const state = body.state && VALID_STATES.has(body.state) ? body.state : existing.state;
  const pendingApproval = existing.approvalRequests[0] ?? null;

  if (OWNER_ONLY_STATES.has(state) && session.user.role !== "owner") {
    return NextResponse.json({ error: "Only owner can set plan to approved/released." }, { status: 403 });
  }

  if (pendingApproval && body.state && body.state !== existing.state && session.user.role !== "owner") {
    return NextResponse.json({ error: "This plan requires owner approval for state transitions." }, { status: 403 });
  }
  if (body.approvalAction && session.user.role !== "owner") {
    return NextResponse.json({ error: "Only owner can approve/reject production plans." }, { status: 403 });
  }

  await prisma.productionPlan.update({
    where: { id: existing.id },
    data: {
      ...(body.lineName !== undefined ? { lineName: body.lineName.trim() || existing.lineName } : {}),
      ...(body.capacityUnits !== undefined ? { capacityUnits: Math.max(0, body.capacityUnits) } : {}),
      ...(body.plannedUnits !== undefined ? { plannedUnits: Math.max(0, body.plannedUnits) } : {}),
      ...(body.forecastUnits !== undefined ? { forecastUnits: Math.max(0, body.forecastUnits) } : {}),
      varianceUnits: varianceUnits(forecastUnits, plannedUnits),
      state,
      ...(state === ProductionPlanState.approved || state === ProductionPlanState.released
        ? {
            approvedById: session.user.role === "owner" ? session.user.id : existing.approvedById,
            approvedAt: session.user.role === "owner" ? new Date() : existing.approvedAt,
          }
        : {}),
    },
  });

  if (state === ProductionPlanState.locked && existing.approvalRequests.length === 0) {
    const ownerUserId = await resolveOwnerUserId();
    await prisma.approvalRequest.create({
      data: {
        department: DepartmentKey.operaciones,
        requestType: "production_plan_lock",
        productionPlanId: existing.id,
        submittedById: session.user.id,
        approverId: ownerUserId,
        state: ApprovalState.pending_owner,
        reason: "Plan locked and awaiting owner approval.",
      },
    });
  }

  if (body.approvalAction && session.user.role === "owner" && existing.approvalRequests.length > 0) {
    const approved = body.approvalAction === "approve";
    const approval = existing.approvalRequests[0];
    await prisma.approvalRequest.update({
      where: { id: approval.id },
      data: {
        state: approved ? ApprovalState.approved : ApprovalState.rejected,
        approverId: session.user.id,
        decidedAt: new Date(),
      },
    });
    await prisma.productionPlan.update({
      where: { id: existing.id },
      data: {
        state: approved ? ProductionPlanState.approved : ProductionPlanState.replanned,
        approvedById: approved ? session.user.id : null,
        approvedAt: approved ? new Date() : null,
      },
    });
  }

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