import { Prisma } from "@prisma/client";
import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { listUserProposals } from "@/lib/proposals/server";

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

function parseString(value: unknown) {
  return typeof value === "string" ? value.trim() : "";
}

function toProposalPayload(
  proposal: {
    id: string;
    title: string;
    issuingEntity: string;
    summary: string;
    status: string;
    sourceLicitationId: string | null;
    createdAt: Date;
    updatedAt: Date;
    documents: Array<{
      id: string;
      fileName: string;
      mimeType: string;
      sizeBytes: number;
      createdAt: Date;
    }>;
  } & {
    currentStep?: number;
    completionPercent?: number;
    readyForSubmissionAt?: Date | null;
  },
) {
  return {
    id: proposal.id,
    title: proposal.title,
    issuingEntity: proposal.issuingEntity,
    summary: proposal.summary,
    currentStep: proposal.currentStep ?? 1,
    completionPercent: proposal.completionPercent ?? 0,
    readyForSubmissionAt: proposal.readyForSubmissionAt ? proposal.readyForSubmissionAt.toISOString() : null,
    status: proposal.status,
    sourceLicitationId: proposal.sourceLicitationId,
    createdAt: proposal.createdAt.toISOString(),
    updatedAt: proposal.updatedAt.toISOString(),
    documents: proposal.documents.map((document) => ({
      id: document.id,
      fileName: document.fileName,
      mimeType: document.mimeType,
      sizeBytes: document.sizeBytes,
      createdAt: document.createdAt.toISOString(),
    })),
  };
}

export async function GET(request: Request) {
  const user = await requireAdminApiUser();

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

  try {
    const url = new URL(request.url);
    const q = url.searchParams.get("q") ?? "";
    const proposals = await listUserProposals(user.id, q);
    return NextResponse.json({ ok: true, proposals });
  } catch (error) {
    if (isSchemaNotReadyError(error)) {
      return NextResponse.json(
        { error: "La base de datos aun no tiene las tablas de Gestion de Licitaciones. Ejecuta prisma migrate para continuar." },
        { status: 503 },
      );
    }

    return NextResponse.json({ error: "No fue posible obtener propuestas." }, { status: 400 });
  }
}

export async function POST(request: Request) {
  const user = await requireAdminApiUser();

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

  try {
    const body = (await request.json()) as Record<string, unknown>;
    const title = parseString(body.title);
    const issuingEntity = parseString(body.issuingEntity);
    const summary = parseString(body.summary);
    const sourceLicitationIdRaw = parseString(body.sourceLicitationId);
    const sourceLicitationId = sourceLicitationIdRaw || null;

    if (!title) {
      return NextResponse.json({ error: "El titulo es requerido." }, { status: 400 });
    }

    if (!issuingEntity) {
      return NextResponse.json({ error: "La entidad emisora es requerida." }, { status: 400 });
    }

    const proposal = await prisma.proposal.create({
      data: {
        userId: user.id,
        title,
        issuingEntity,
        summary,
        sourceLicitationId,
      },
      select: {
        id: true,
        title: true,
        issuingEntity: true,
        summary: true,
        status: true,
        sourceLicitationId: true,
        createdAt: true,
        updatedAt: true,
        documents: {
          orderBy: [{ createdAt: "desc" }],
          select: {
            id: true,
            fileName: true,
            mimeType: true,
            sizeBytes: true,
            createdAt: true,
          },
        },
      },
    });

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

    return NextResponse.json({ error: "No fue posible crear la propuesta." }, { status: 400 });
  }
}
