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

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

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

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 });
  }

  const assets = await prisma.factoryAsset.findMany({
    where: { department: DepartmentKey.operaciones },
    orderBy: [{ state: "asc" }, { updatedAt: "desc" }],
    take: 500,
  });

  return NextResponse.json({
    ok: true,
    assets: assets.map((asset) => ({
      id: asset.id,
      assetCode: asset.assetCode,
      name: asset.name,
      category: asset.category,
      locationId: asset.locationId,
      criticality: asset.criticality,
      state: asset.state,
      serviceStrategy: asset.serviceStrategy,
      lastMaintenanceAt: asset.lastMaintenanceAt ? asset.lastMaintenanceAt.toISOString() : null,
      nextMaintenanceAt: asset.nextMaintenanceAt ? asset.nextMaintenanceAt.toISOString() : null,
      createdAt: asset.createdAt.toISOString(),
      updatedAt: asset.updatedAt.toISOString(),
    })),
  });
}

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

  const body = (await request.json()) as CreateAssetBody;
  const name = body.name?.trim() ?? "";
  const category = body.category?.trim() ?? "";
  const state = body.state && VALID_STATES.has(body.state) ? body.state : FactoryAssetState.active;
  const criticality = Math.max(1, Math.min(5, Math.round(body.criticality ?? 3)));
  const nextMaintenanceAt = body.nextMaintenanceAt ? new Date(body.nextMaintenanceAt) : null;
  const assetCode = body.assetCode?.trim() || `ASSET-${Date.now()}`;

  if (!name || !category) {
    return NextResponse.json({ error: "name and category are required." }, { status: 400 });
  }

  const asset = await prisma.factoryAsset.create({
    data: {
      department: DepartmentKey.operaciones,
      assetCode,
      name,
      category,
      locationId: body.locationId?.trim() || null,
      criticality,
      state,
      serviceStrategy: body.serviceStrategy?.trim() || null,
      nextMaintenanceAt: nextMaintenanceAt && !Number.isNaN(nextMaintenanceAt.getTime()) ? nextMaintenanceAt : null,
      createdById: session.user.id,
    },
  });

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