/**
 * OCDS 1.1.5 Single Release — by announcement id.
 * GET /api/ocds/release/{id}
 * Returns a Release Package containing one release.
 */
import type { APIRoute } from 'astro';
import { query } from '../../../../lib/db.js';
import { buildSingleReleasePackage, type AnnouncementRow } from '../../../../lib/ocds-mapper.js';
import { publicOrigin } from '../../../../lib/public-url.js';

export const prerender = false;

export const GET: APIRoute = async ({ params, url, request }) => {
  const idStr = params.id as string;
  // Accept both raw id and ocid format (ocds-vreaudigital-{id})
  const id = parseInt((idStr || '').replace(/^ocds-vreaudigital-/, ''));
  if (isNaN(id)) {
    return new Response(JSON.stringify({ error: 'Invalid release id' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' },
    });
  }

  try {
    const result = await query<AnnouncementRow>(`
      SELECT
        a.id, a.ref_number, a.type, a.source, a.title, a.description,
        a.publication_date, a.contract_date,
        a.estimated_value, a.awarded_value, a.currency,
        a.procedure_type, a.procedure_state,
        a.framework_agreement, a.modification_desc,
        a.cpv_code, a.cpv_name, a.cpv_division,
        a.authority_cui, a.authority_name, a.authority_address,
        a.authority_email, a.authority_phone, a.authority_url,
        acl.county AS authority_county, a.authority_siruta,
        a.supplier_cui, a.supplier_name, a.supplier_address,
        scl.county AS supplier_county, a.supplier_siruta,
        a.supplier_is_sme, a.contract_has_lots, a.lots_count,
        a.seap_url
      FROM seap.announcements a
      LEFT JOIN seap.cui_location acl ON acl.cui = a.authority_cui
      LEFT JOIN seap.cui_location scl ON scl.cui = regexp_replace(upper(a.supplier_cui), '(^RO)|\\s+', '', 'g')
      WHERE a.id = $1
    `, [id]);

    if (result.rows.length === 0) {
      return new Response(JSON.stringify({ error: 'Release not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' },
      });
    }

    const requestUri = `${publicOrigin(request, url)}${url.pathname}${url.search}`;
    const pkg = buildSingleReleasePackage(result.rows[0], requestUri);

    return new Response(JSON.stringify(pkg, null, 2), {
      status: 200,
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'Access-Control-Allow-Origin': '*',
        'Cache-Control': 'public, max-age=3600, s-maxage=86400',
      },
    });
  } catch (err: any) {
    console.error('[/api/ocds/release/:id]', err);
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    });
  }
};
