import { eq } from "drizzle-orm";
import { getDb } from "@/db";
import { orders } from "@/db/schema";
import { catalogEntryForTier } from "@/lib/commerce";

type StripeSession = {
  id?: string;
  mode?: string;
  status?: string;
  payment_status?: string;
  client_reference_id?: string;
  amount_total?: number;
  currency?: string;
  customer_details?: { email?: string };
  metadata?: Record<string, string>;
  error?: { message?: string };
};

function validSessionId(value: string) {
  return /^cs_(?:test_|live_)?[A-Za-z0-9]{20,180}$/.test(value);
}

export async function GET(request: Request) {
  const secret = process.env.STRIPE_SECRET_KEY;
  if (!secret) return Response.json({ error: "Confirmação indisponível por configuração incompleta." }, { status: 503 });
  const sessionId = new URL(request.url).searchParams.get("session_id") || "";
  if (!validSessionId(sessionId)) return Response.json({ error: "Referência de pagamento inválida." }, { status: 400 });

  try {
    const db = getDb();
    const stored = await db.select().from(orders).where(eq(orders.stripeSessionId, sessionId)).limit(1);
    if (!stored.length || stored[0].paymentStatus !== "paid") {
      return Response.json({ status: "processing" }, { status: 202, headers: { "cache-control": "no-store" } });
    }

    const response = await fetch(`https://api.stripe.com/v1/checkout/sessions/${encodeURIComponent(sessionId)}`, {
      headers: { authorization: `Bearer ${secret}` },
    });
    const session = (await response.json()) as StripeSession;
    if (!response.ok || session.id !== sessionId) {
      console.error("stripe_confirmation_lookup_failed", session.error?.message || response.status);
      return Response.json({ error: "Não foi possível confirmar o pagamento." }, { status: 502 });
    }
    const order = stored[0];
    const catalogEntry = catalogEntryForTier(order.ticketTier);
    const reference = session.metadata?.order_public_id || session.client_reference_id || "";
    const reconciled = session.mode === "payment" && session.status === "complete" && session.payment_status === "paid"
      && Boolean(catalogEntry) && reference === order.publicId
      && session.amount_total === order.amountTotal && session.currency?.toLowerCase() === order.currency;
    if (!reconciled) {
      console.error("stripe_confirmation_reconciliation_failed", sessionId);
      return Response.json({ error: "A confirmação não passou na reconciliação de segurança." }, { status: 409 });
    }
    return Response.json({
      status: "paid",
      reference: order.publicId,
      ticketTier: order.ticketTier,
      amountTotal: order.amountTotal,
      currency: order.currency,
      email: session.customer_details?.email || order.customerEmail || null,
    }, { headers: { "cache-control": "no-store" } });
  } catch (error) {
    console.error("checkout_confirmation_failed", error);
    return Response.json({ error: "Não foi possível confirmar o pagamento agora." }, { status: 500 });
  }
}

