-- 017_fonduri_afir.sql
-- AFIR (Agenția pentru Finanțarea Investițiilor Rurale) plăți FEGA + FEADR.
-- Source: https://www.afir.ro/rapoarte/beneficiari-de-fonduri-europene/date-deschise/
-- Format: XLSX bulk per year, ~560K rows/year, no direct CUI column.
-- Strategy: load all rows, then fuzzy-match name → cui in a separate batch job.

CREATE SCHEMA IF NOT EXISTS fonduri;

CREATE TABLE IF NOT EXISTS fonduri.afir_plati (
  id                 BIGSERIAL PRIMARY KEY,
  source_year        smallint NOT NULL,
  beneficiar_name    text NOT NULL,
  last_name          text,                       -- empty for legal entities
  mama_cui           text,                       -- mother company name + CUI when applicable (mostly empty)
  localitate         text,
  cod_masura         text,
  obiectiv           text,
  data_start         text,
  data_end           text,
  fega_op            numeric(20,2),
  fega_total         numeric(20,2),
  feadr_op           numeric(20,2),
  feadr_total        numeric(20,2),
  op_amount          numeric(20,2),
  cofinantare        numeric(20,2),
  ue_total           numeric(20,2),
  -- Enrichment (filled by separate matcher):
  cui                text,
  cui_match_score    real,
  cui_match_method   text,
  matched_at         timestamptz,
  fetched_at         timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_afir_year ON fonduri.afir_plati(source_year);
CREATE INDEX IF NOT EXISTS idx_afir_cui ON fonduri.afir_plati(cui) WHERE cui IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_afir_cod_masura ON fonduri.afir_plati(cod_masura);
CREATE INDEX IF NOT EXISTS idx_afir_localitate ON fonduri.afir_plati(localitate);
CREATE INDEX IF NOT EXISTS idx_afir_name_trgm ON fonduri.afir_plati USING gin (beneficiar_name gin_trgm_ops);

-- Staging table for COPY (no PK, all text)
CREATE TABLE IF NOT EXISTS fonduri.staging_afir (
  beneficiar_name text,
  last_name       text,
  mama_cui        text,
  localitate      text,
  cod_masura      text,
  obiectiv        text,
  data_start      text,
  data_end        text,
  fega_op         text,
  fega_total      text,
  feadr_op        text,
  feadr_total     text,
  op_amount       text,
  cofinantare     text,
  ue_total        text
);
