import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";

interface Preso {
  rg: string;
  nome: string;
  foto: string | null;
}

interface Historico {
  id: number;
  artigos: string;
  multa_total: number;
  pena_total: number;
  oficial: string;
  created_at: string;
}

export async function GET(req: NextRequest) {
  const rg = req.nextUrl.searchParams.get("rg")?.trim() || "";
  if (!rg) return NextResponse.json({ found: false });

  const rows = (await query("SELECT rg, nome, foto FROM presos WHERE rg = ?", [rg])) as Preso[];
  if (rows.length === 0) return NextResponse.json({ found: false });

  const preso = rows[0];
  const historico = (await query(
    "SELECT id, artigos, multa_total, pena_total, oficial, created_at FROM historico_prisoes WHERE rg_preso = ? ORDER BY created_at DESC LIMIT 10",
    [rg]
  )) as Historico[];

  return NextResponse.json({
    found: true,
    nome: preso.nome,
    rg: preso.rg,
    foto: preso.foto,
    reincidente: historico.length > 0,
    total_prisoes: historico.length,
    historico,
  });
}
