import { signatureMatchesStored, verifyTicketSignature } from "@/lib/ticket-signing";
import { getTicketCardData } from "@db/queries/orders";
import { getCachedTicketCardPng } from "@/lib/ticket-card-render";

// Flattened wallet-card PNG of a ticket, embedded via <img src> in the
// confirmation email instead of an HTML/table reconstruction -- guarantees
// identical rendering across Gmail/Outlook/Apple Mail since it's a single
// image, not markup those clients interpret differently. Signature-gated
// the same way /api/tickets/qr is; attendee name/phone/event details are
// looked up server-side from the code, never passed as query params (PII
// must never travel in a URL). The render itself is cached to disk (see
// getCachedTicketCardPng) and pre-warmed at email-send time, so this route
// is almost always a fast cache read, not a cold render.
export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const code = searchParams.get("code");
  const signature = searchParams.get("signature");

  if (!code || !signature) return new Response("Not found", { status: 404 });

  // Tickets carried over from before a TICKET_SIGNING_SECRET change carry a
  // signature that only matches the one stored on their row -- accept that
  // too (same rule as /api/checkin), or their email QR images 404.
  const data = await getTicketCardData(code);
  if (!data || !(verifyTicketSignature(code, signature) || signatureMatchesStored(signature, data.signature))) {
    return new Response("Not found", { status: 404 });
  }

  const buffer = await getCachedTicketCardPng({
    code: data.code,
    signature,
    attendeeName: data.attendeeName,
    buyerPhone: data.buyerPhone,
    ticketTypeName: data.ticketTypeName,
    eventTitle: data.eventTitle,
    venue: data.venue,
    city: data.city,
    startsAt: data.startsAt,
    endsAt: data.endsAt,
    organizerName: data.organizerName,
    coverImageUrl: data.coverImageUrl,
    index: data.index,
  });

  return new Response(new Uint8Array(buffer), {
    headers: {
      "Content-Type": "image/png",
      "Cache-Control": "public, max-age=31536000, immutable",
    },
  });
}
