import { Prisma, type LicitationReviewStatus } from "@prisma/client";
import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { parseLicitationReviewStatus } from "@/lib/licitations/preferences";
import { prisma } from "@/lib/prisma";

function isSchemaNotReadyError(error: unknown) {
  return error instanceof Prisma.PrismaClientKnownRequestError && (error.code === "P2021" || error.code === "P2022");
}

export async function PATCH(request: Request, context: { params: Promise<{ id: string }> }) {
  const user = await requireAdminApiUser();

  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const { id } = await context.params;
    const body = (await request.json()) as Record<string, unknown>;
    const status = parseLicitationReviewStatus(body.status);

    if (!status) {
      return NextResponse.json({ error: "Estatus invalido." }, { status: 400 });
    }

    const licitation = await prisma.licitation.findUnique({
      where: { id },
      select: { id: true },
    });

    if (!licitation) {
      return NextResponse.json({ error: "Licitacion no encontrada." }, { status: 404 });
    }

    if (status === "NEW") {
      await prisma.licitationUserPreference.deleteMany({
        where: {
          userId: user.id,
          licitationId: id,
        },
      });

      return NextResponse.json({ ok: true, status: "NEW" });
    }

    const updated = await prisma.licitationUserPreference.upsert({
      where: {
        userId_licitationId: {
          userId: user.id,
          licitationId: id,
        },
      },
      update: {
        status: status as LicitationReviewStatus,
      },
      create: {
        userId: user.id,
        licitationId: id,
        status: status as LicitationReviewStatus,
      },
      select: {
        status: true,
      },
    });

    return NextResponse.json({ ok: true, status: updated.status });
  } catch (error) {
    if (isSchemaNotReadyError(error)) {
      return NextResponse.json(
        { error: "La base de datos aun no tiene las tablas de estado de oportunidades. Ejecuta prisma migrate para continuar." },
        { status: 503 },
      );
    }

    return NextResponse.json({ error: "No fue posible actualizar el estado." }, { status: 400 });
  }
}
