-- 043_red_flags_kpi_snapshot.sql
-- Materialize red-flags landing KPI counters to a static refresh table.
-- Original page was 30s with all KPI INTERSECTs + 13 recipe fetches running.
-- KPI INTERSECTs (TRIPLE/QUADRA pipe etc.) alone = 12s. Now ~1ms read.
--
-- Refresh: nightly via mvs cron at 04:00 (or add to refresh-mvs.sh).

CREATE SCHEMA IF NOT EXISTS public_kpi;

CREATE TABLE IF NOT EXISTS public_kpi.red_flags_counts (
  k_name text PRIMARY KEY,
  k_value bigint NOT NULL,
  refreshed_at timestamptz NOT NULL DEFAULT now()
);

COMMENT ON TABLE public_kpi.red_flags_counts IS
  'KPI counters surfaced on /achizitii/red-flags landing. Refreshed nightly. Page reads as a single SELECT to avoid 12s INTERSECT cost.';

-- Refresh function — called by cron
CREATE OR REPLACE FUNCTION public_kpi.refresh_red_flags_counts() RETURNS void AS $$
BEGIN
  INSERT INTO public_kpi.red_flags_counts (k_name, k_value, refreshed_at) VALUES
    ('regas_seap_firms',
      (SELECT count(DISTINCT cui) FROM regas.ajutoare WHERE cui IS NOT NULL
        AND cui IN (SELECT supplier_cui FROM seap.announcements WHERE supplier_cui IS NOT NULL)),
      now()),
    ('regas_seap_records',
      (SELECT count(*) FROM regas.ajutoare WHERE cui IS NOT NULL
        AND cui IN (SELECT supplier_cui FROM seap.announcements WHERE supplier_cui IS NOT NULL)),
      now()),
    ('ben_seap_firms',
      (SELECT count(DISTINCT cui) FROM fonduri.beneficiar_anunt WHERE cui IS NOT NULL
        AND cui IN (SELECT supplier_cui FROM seap.announcements WHERE supplier_cui IS NOT NULL)),
      now()),
    ('datornic_seap_firms',
      (SELECT count(DISTINCT d.cui) FROM anaf.datornici d
        JOIN seap.announcements a ON a.supplier_cui = d.cui
        AND a.publication_date::date > d.publication_date
        AND a.awarded_value > 100000),
      now()),
    ('aep_seap_firms',
      (SELECT count(DISTINCT donator_cui) FROM aep.donatii_pj
        WHERE donator_cui IS NOT NULL
        AND donator_cui IN (SELECT supplier_cui FROM seap.announcements WHERE supplier_cui IS NOT NULL AND awarded_value > 100000)),
      now()),
    ('triple_firms',
      (SELECT count(*) FROM (
        SELECT b.cui FROM fonduri.beneficiar_anunt b WHERE cui IS NOT NULL
        INTERSECT SELECT supplier_cui FROM seap.announcements WHERE supplier_cui IS NOT NULL
        INTERSECT SELECT cui FROM fonduri.afir_plati WHERE cui IS NOT NULL
      ) t),
      now()),
    ('quadra_firms',
      (SELECT count(*) FROM (
        SELECT b.cui FROM fonduri.beneficiar_anunt b WHERE cui IS NOT NULL
        INTERSECT SELECT supplier_cui FROM seap.announcements WHERE supplier_cui IS NOT NULL
        INTERSECT SELECT cui FROM fonduri.afir_plati WHERE cui IS NOT NULL
        INTERSECT SELECT cui FROM regas.ajutoare WHERE cui IS NOT NULL
      ) t),
      now()),
    ('donator_datornic_firms',
      (SELECT count(DISTINCT a.donator_cui) FROM aep.donatii_pj a
        JOIN anaf.datornici_latest d ON d.cui = a.donator_cui),
      now()),
    ('anre_datornic_firms',
      (SELECT count(DISTINCT a.cui) FROM anre.mv_licente_per_cui a
        JOIN anaf.datornici_latest d ON d.cui = a.cui WHERE a.nr_active > 0),
      now()),
    ('dubla_alerta_firms',
      (SELECT count(*) FROM (
        SELECT audited_entity_cui AS cui FROM curteacont.rapoarte
         WHERE audited_entity_cui IS NOT NULL AND publication_date >= now() - interval '5 years'
         GROUP BY audited_entity_cui HAVING count(*) >= 2
        INTERSECT
        SELECT cui FROM cnsc.mv_per_authority_cui WHERE contestation_count >= 3
      ) t),
      now())
  ON CONFLICT (k_name) DO UPDATE
  SET k_value = EXCLUDED.k_value,
      refreshed_at = EXCLUDED.refreshed_at;
END;
$$ LANGUAGE plpgsql;

-- Initial populate
SELECT public_kpi.refresh_red_flags_counts();

SELECT k_name, k_value, refreshed_at FROM public_kpi.red_flags_counts ORDER BY k_name;
