import type { APIRoute } from 'astro';
import { getSupplierProfile } from '../../../../lib/profile-queries.js';
import { ogProfileImage } from '../../../../lib/og-image.js';

export const prerender = false;

function fmtRon(v: number | null | undefined): string {
  if (v == null) return '0';
  if (v >= 1_000_000_000) return `${(v / 1_000_000_000).toFixed(1)} mld`;
  if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)} mil`;
  if (v >= 1_000) return `${(v / 1_000).toFixed(0)}K`;
  return Math.round(v).toString();
}

export const GET: APIRoute = async ({ params }) => {
  const cui = (params.cui as string).replace(/^RO\s*/i, '').trim();
  const profile = await getSupplierProfile(cui);

  if (!profile) return new Response('Not found', { status: 404 });

  try {
    const png = await ogProfileImage({
      kind: 'firma',
      name: profile.name || `CUI ${cui}`,
      cui: profile.cui,
      totalValue: fmtRon(Number(profile.total_awarded)),
      contracts: profile.contracts_won,
    });
    return new Response(png as any, {
      status: 200,
      headers: { 'Content-Type': 'image/png', 'Cache-Control': 'public, max-age=3600, s-maxage=86400' },
    });
  } catch (err: any) {
    console.error('[OG firma]', err);
    return new Response('Render error', { status: 500 });
  }
};
