/**
 * OCDS 1.1.5 Release Package — paginated list endpoint.
 *
 * GET /api/ocds/releases?limit=100&offset=0&since=2024-01-01&authority_cui=123&supplier_cui=456
 *   limit:         max 500, default 100
 *   offset:        default 0
 *   since:         ISO date — releases.date >= since
 *   until:         ISO date — releases.date <= until
 *   authority_cui: filter by buyer CUI
 *   supplier_cui:  filter by supplier CUI
 *
 * Response: standard OCDS Release Package JSON.
 * License: CC-BY 4.0. See /api/ocds/policy.
 */
import type { APIRoute } from 'astro';
import { query } from '../../../lib/db.js';
import { buildReleasePackage, type AnnouncementRow } from '../../../lib/ocds-mapper.js';
import { publicOrigin } from '../../../lib/public-url.js';

export const prerender = false;

const FIELDS = `
  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
`;

export const GET: APIRoute = async ({ url, request }) => {
  const limit = Math.min(parseInt(url.searchParams.get('limit') || '100'), 500);
  const offset = parseInt(url.searchParams.get('offset') || '0');
  const since = url.searchParams.get('since');
  const until = url.searchParams.get('until');
  const authorityCui = url.searchParams.get('authority_cui');
  const supplierCui = url.searchParams.get('supplier_cui');

  const where: string[] = [];
  const params: any[] = [];
  let p = 0;

  if (since) { params.push(since); where.push(`a.publication_date >= $${++p}`); }
  if (until) { params.push(until); where.push(`a.publication_date <= $${++p}`); }
  if (authorityCui) {
    const norm = authorityCui.toUpperCase().replace(/^RO/, '').replace(/\s+/g, '').trim();
    params.push(norm);
    where.push(`regexp_replace(upper(a.authority_cui), '(^RO)|\\s+', '', 'g') = $${++p}`);
  }
  if (supplierCui) {
    const norm = supplierCui.toUpperCase().replace(/^RO/, '').replace(/\s+/g, '').trim();
    params.push(norm);
    where.push(`regexp_replace(upper(a.supplier_cui), '(^RO)|\\s+', '', 'g') = $${++p}`);
  }

  const whereClause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';

  params.push(limit);
  params.push(offset);

  const sql = `
    SELECT ${FIELDS}
    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')
    ${whereClause}
    ORDER BY a.publication_date DESC NULLS LAST, a.id DESC
    LIMIT $${++p} OFFSET $${++p}
  `;

  try {
    const result = await query<AnnouncementRow>(sql, params);
    const origin = publicOrigin(request, url);
    const requestUri = `${origin}${url.pathname}${url.search}`;
    const pkg = buildReleasePackage(result.rows, requestUri);

    // Add pagination links per OCDS spec
    const baseUrl = `${origin}${url.pathname}`;
    const qs = new URLSearchParams(url.searchParams);
    qs.set('limit', String(limit));
    qs.set('offset', String(offset + limit));
    pkg.links = {
      next: result.rows.length === limit ? `${baseUrl}?${qs.toString()}` : undefined,
    };
    pkg.meta = {
      count: result.rows.length,
      limit,
      offset,
    };

    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=300, s-maxage=600',
      },
    });
  } catch (err: any) {
    console.error('[/api/ocds/releases]', err);
    return new Response(JSON.stringify({ error: 'Internal server error', detail: err.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    });
  }
};
