import type { APIRoute } from 'astro';
import {
  getAuthorityProfile,
  getSupplierProfile,
  getAuthorityContracts,
  getSupplierContracts,
  getCpvBreakdown,
  getTopCounterparts,
  getMonthlyTimeline,
} from '../../../../lib/profile-queries.js';

export const prerender = false;

const json = (data: any, status = 200) =>
  new Response(JSON.stringify(data), {
    status,
    headers: {
      'Content-Type': 'application/json',
      'Cache-Control': 'public, max-age=300',
    },
  });

export const GET: APIRoute = async ({ params, url }) => {
  const side = params.side as 'autoritate' | 'firma';
  const cui = params.cui as string;
  if (!side || !cui) return json({ error: 'Missing side or cui' }, 400);
  if (!['autoritate', 'firma'].includes(side))
    return json({ error: 'Side must be autoritate or firma' }, 400);

  const sideKey: 'authority' | 'supplier' = side === 'autoritate' ? 'authority' : 'supplier';
  const limit = parseInt(url.searchParams.get('limit') || '50');
  const offset = parseInt(url.searchParams.get('offset') || '0');

  try {
    if (sideKey === 'authority') {
      const [profile, contracts, cpv, suppliers, timeline] = await Promise.all([
        getAuthorityProfile(cui),
        getAuthorityContracts(cui, limit, offset),
        getCpvBreakdown('authority', cui),
        getTopCounterparts('authority', cui, 10),
        getMonthlyTimeline('authority', cui),
      ]);
      if (!profile) return json({ error: 'Autoritatea nu a fost găsită' }, 404);
      return json({ profile, contracts, cpv, top_counterparts: suppliers, timeline });
    } else {
      const [profile, contracts, cpv, buyers, timeline] = await Promise.all([
        getSupplierProfile(cui),
        getSupplierContracts(cui, limit, offset),
        getCpvBreakdown('supplier', cui),
        getTopCounterparts('supplier', cui, 10),
        getMonthlyTimeline('supplier', cui),
      ]);
      if (!profile) return json({ error: 'Firma nu a fost găsită' }, 404);
      return json({ profile, contracts, cpv, top_counterparts: buyers, timeline });
    }
  } catch (err: any) {
    console.error(`[API /profil/${side}/${cui}]`, err);
    return json({ error: 'Internal server error', detail: err.message }, 500);
  }
};
