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

type UpdateAssetBody = {
  name?: string;
  category?: string;
  locationId?: string | null;
  criticality?: number;
  state?: FactoryAssetState;
  serviceStrategy?: string | null;
  nextMaintenanceAt?: string | null;
  lastMaintenanceAt?: string | null;
};

const VALID_STATES = new Set<FactoryAssetState>([
  FactoryAssetState.draft,
  FactoryAssetState.active,
  FactoryAssetState.down,
  FactoryAssetState.retired,
]);

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

  const body = (await request.json()) as UpdateAssetBody;
  const nextMaintenanceAt = body.nextMaintenanceAt ? new Date(body.nextMaintenanceAt) : null;
  const lastMaintenanceAt = body.lastMaintenanceAt ? new Date(body.lastMaintenanceAt) : null;
  const existing = await prisma.factoryAsset.findFirst({
    where: {
      id: context.params.id,
      department: DepartmentKey.operaciones,
    },
    select: { id: true },
  });
  if (!existing) {
    return NextResponse.json({ error: "Asset not found in operations department." }, { status: 404 });
  }

  const asset = await prisma.factoryAsset.update({
    where: { id: existing.id },
    data: {
      ...(body.name !== undefined ? { name: body.name.trim() || "Asset" } : {}),
      ...(body.category !== undefined ? { category: body.category.trim() || "General" } : {}),
      ...(body.locationId !== undefined ? { locationId: body.locationId?.trim() || null } : {}),
      ...(body.criticality !== undefined ? { criticality: Math.max(1, Math.min(5, Math.round(body.criticality))) } : {}),
      ...(body.state !== undefined && VALID_STATES.has(body.state) ? { state: body.state } : {}),
      ...(body.serviceStrategy !== undefined ? { serviceStrategy: body.serviceStrategy?.trim() || null } : {}),
      ...(body.nextMaintenanceAt !== undefined
        ? { nextMaintenanceAt: nextMaintenanceAt && !Number.isNaN(nextMaintenanceAt.getTime()) ? nextMaintenanceAt : null }
        : {}),
      ...(body.lastMaintenanceAt !== undefined
        ? { lastMaintenanceAt: lastMaintenanceAt && !Number.isNaN(lastMaintenanceAt.getTime()) ? lastMaintenanceAt : null }
        : {}),
    },
  });

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

export async function DELETE(_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 delete assets." }, { status: 403 });
  }

  const deleted = await prisma.factoryAsset.deleteMany({
    where: {
      id: context.params.id,
      department: DepartmentKey.operaciones,
    },
  });
  if (deleted.count === 0) {
    return NextResponse.json({ error: "Asset not found in operations department." }, { status: 404 });
  }

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