-- ============================================================
-- Verification for HMM demo carrier performance data.
-- Redmine: #729
-- ============================================================

\set ON_ERROR_STOP on
\pset pager off
\echo === HMM carrier performance demo: verification begin ===

DO $verify$
DECLARE
  carrier_count       INTEGER;
  performance_count   INTEGER;
  invalid_month_count INTEGER;
  latest_month        DATE;
  earliest_month      DATE;
  wrong_series_count  INTEGER;
  latest_risk_count   INTEGER;
  wrong_trend_count   INTEGER;
  reader_can_login    BOOLEAN;
BEGIN
  SELECT COUNT(*)
    INTO carrier_count
    FROM hmm_demo.carriers
   WHERE carrier_code BETWEEN 'C001' AND 'C008';

  SELECT COUNT(*), MIN(performance_month), MAX(performance_month)
    INTO performance_count, earliest_month, latest_month
    FROM hmm_demo.carrier_monthly_performance
   WHERE carrier_code BETWEEN 'C001' AND 'C008'
     AND performance_month BETWEEN DATE '2025-02-01' AND DATE '2026-07-01';

  SELECT COUNT(*)
    INTO invalid_month_count
    FROM hmm_demo.carrier_monthly_performance
   WHERE performance_month <> date_trunc('month', performance_month)::DATE;

  SELECT COUNT(*)
    INTO wrong_series_count
    FROM (
      SELECT carrier_code, COUNT(*) AS month_count
        FROM hmm_demo.carrier_monthly_performance
       WHERE carrier_code BETWEEN 'C001' AND 'C008'
         AND performance_month BETWEEN DATE '2025-02-01' AND DATE '2026-07-01'
       GROUP BY carrier_code
      HAVING COUNT(*) <> 18
    ) wrong_series;

  SELECT COUNT(DISTINCT risk_level)
    INTO latest_risk_count
    FROM hmm_demo.carrier_performance_latest_v;

  WITH boundaries AS (
    SELECT
      carrier_code,
      MAX(revenue_usd) FILTER (WHERE performance_month = DATE '2025-02-01')
        AS first_revenue,
      MAX(revenue_usd) FILTER (WHERE performance_month = DATE '2026-07-01')
        AS latest_revenue
    FROM hmm_demo.carrier_monthly_performance
    WHERE carrier_code BETWEEN 'C001' AND 'C008'
    GROUP BY carrier_code
  )
  SELECT COUNT(*)
    INTO wrong_trend_count
    FROM boundaries
   WHERE (carrier_code IN ('C001', 'C002', 'C003', 'C004', 'C007')
          AND latest_revenue <= first_revenue)
      OR (carrier_code IN ('C005', 'C006', 'C008')
          AND latest_revenue >= first_revenue);

  SELECT rolcanlogin
    INTO reader_can_login
    FROM pg_roles
   WHERE rolname = 'hmm_federation_reader';

  IF carrier_count <> 8 THEN
    RAISE EXCEPTION 'Expected 8 carriers, found %', carrier_count;
  END IF;
  IF performance_count <> 144 THEN
    RAISE EXCEPTION 'Expected 144 monthly performance rows, found %', performance_count;
  END IF;
  IF earliest_month <> DATE '2025-02-01' OR latest_month <> DATE '2026-07-01' THEN
    RAISE EXCEPTION 'Unexpected period: % through %', earliest_month, latest_month;
  END IF;
  IF invalid_month_count <> 0 OR wrong_series_count <> 0 THEN
    RAISE EXCEPTION
      'Invalid monthly series: invalid dates %, wrong carrier series %',
      invalid_month_count,
      wrong_series_count;
  END IF;
  IF latest_risk_count <> 3 THEN
    RAISE EXCEPTION 'Expected GREEN, AMBER, RED latest risks, found % levels',
      latest_risk_count;
  END IF;
  IF wrong_trend_count <> 0 THEN
    RAISE EXCEPTION 'Unexpected first-to-latest trend for % carriers', wrong_trend_count;
  END IF;
  IF reader_can_login IS DISTINCT FROM FALSE THEN
    RAISE EXCEPTION 'hmm_federation_reader must remain a NOLOGIN role';
  END IF;

  IF NOT has_schema_privilege('hmm_federation_reader', 'hmm_demo', 'USAGE') THEN
    RAISE EXCEPTION 'hmm_federation_reader lacks schema USAGE';
  END IF;
  IF has_schema_privilege('hmm_federation_reader', 'hmm_demo', 'CREATE') THEN
    RAISE EXCEPTION 'hmm_federation_reader unexpectedly has schema CREATE';
  END IF;
  IF NOT has_table_privilege(
      'hmm_federation_reader',
      'hmm_demo.carrier_monthly_performance',
      'SELECT'
  ) THEN
    RAISE EXCEPTION 'hmm_federation_reader lacks SELECT';
  END IF;
  IF has_table_privilege(
      'hmm_federation_reader',
      'hmm_demo.carrier_monthly_performance',
      'INSERT'
  ) THEN
    RAISE EXCEPTION 'hmm_federation_reader unexpectedly has INSERT';
  END IF;
END
$verify$;

DO $constraint_tests$
BEGIN
  BEGIN
    INSERT INTO hmm_demo.carrier_monthly_performance (
      carrier_code,
      performance_month,
      contracted_teu,
      shipped_teu,
      revenue_usd,
      gross_margin_usd,
      schedule_reliability_pct,
      vessel_utilization_pct,
      claim_rate_pct,
      yoy_growth_pct,
      risk_level,
      updated_at
    ) VALUES (
      'C001',
      DATE '2026-07-02',
      1,
      1,
      1,
      1,
      90,
      90,
      1,
      1,
      'GREEN',
      CURRENT_TIMESTAMP
    );
    RAISE EXCEPTION 'Month-first-day constraint did not reject invalid input';
  EXCEPTION
    WHEN check_violation THEN
      NULL;
  END;

  BEGIN
    INSERT INTO hmm_demo.carrier_monthly_performance (
      carrier_code,
      performance_month,
      contracted_teu,
      shipped_teu,
      revenue_usd,
      gross_margin_usd,
      schedule_reliability_pct,
      vessel_utilization_pct,
      claim_rate_pct,
      yoy_growth_pct,
      risk_level,
      updated_at
    ) VALUES (
      'UNKNOWN',
      DATE '2026-08-01',
      1,
      1,
      1,
      1,
      90,
      90,
      1,
      1,
      'GREEN',
      CURRENT_TIMESTAMP
    );
    RAISE EXCEPTION 'Foreign key constraint did not reject unknown carrier';
  EXCEPTION
    WHEN foreign_key_violation THEN
      NULL;
  END;

  BEGIN
    INSERT INTO hmm_demo.carrier_monthly_performance (
      carrier_code,
      performance_month,
      contracted_teu,
      shipped_teu,
      revenue_usd,
      gross_margin_usd,
      schedule_reliability_pct,
      vessel_utilization_pct,
      claim_rate_pct,
      yoy_growth_pct,
      risk_level,
      updated_at
    ) VALUES (
      'C001',
      DATE '2026-08-01',
      1,
      1,
      1,
      1,
      101,
      90,
      1,
      1,
      'GREEN',
      CURRENT_TIMESTAMP
    );
    RAISE EXCEPTION 'Percentage constraint did not reject invalid input';
  EXCEPTION
    WHEN check_violation THEN
      NULL;
  END;
END
$constraint_tests$;

\echo --- Row counts and period ---
SELECT
  COUNT(DISTINCT carrier_code) AS carrier_count,
  COUNT(*) AS monthly_row_count,
  MIN(performance_month) AS first_month,
  MAX(performance_month) AS latest_month
FROM hmm_demo.carrier_monthly_performance
WHERE carrier_code BETWEEN 'C001' AND 'C008'
  AND performance_month BETWEEN DATE '2025-02-01' AND DATE '2026-07-01';

\echo --- Per-carrier series ---
SELECT
  c.carrier_code,
  c.carrier_name,
  COUNT(p.*) AS month_count,
  MIN(p.performance_month) AS first_month,
  MAX(p.performance_month) AS latest_month
FROM hmm_demo.carriers c
JOIN hmm_demo.carrier_monthly_performance p
  ON p.carrier_code = c.carrier_code
WHERE c.carrier_code BETWEEN 'C001' AND 'C008'
GROUP BY c.carrier_code, c.carrier_name
ORDER BY c.carrier_code;

\echo --- Latest KPI and risk distribution ---
SELECT
  carrier_code,
  carrier_name,
  performance_month,
  shipped_teu,
  revenue_usd,
  gross_margin_usd,
  schedule_reliability_pct,
  claim_rate_pct,
  risk_level
FROM hmm_demo.carrier_performance_latest_v
ORDER BY carrier_code;

SELECT risk_level, COUNT(*) AS carrier_count
FROM hmm_demo.carrier_performance_latest_v
GROUP BY risk_level
ORDER BY risk_level;

\echo --- First-to-latest revenue trend ---
WITH boundaries AS (
  SELECT
    carrier_code,
    MAX(revenue_usd) FILTER (WHERE performance_month = DATE '2025-02-01') AS first_revenue,
    MAX(revenue_usd) FILTER (WHERE performance_month = DATE '2026-07-01') AS latest_revenue
  FROM hmm_demo.carrier_monthly_performance
  WHERE carrier_code BETWEEN 'C001' AND 'C008'
  GROUP BY carrier_code
)
SELECT
  carrier_code,
  first_revenue,
  latest_revenue,
  CASE
    WHEN latest_revenue > first_revenue THEN 'UP'
    WHEN latest_revenue < first_revenue THEN 'DOWN'
    ELSE 'FLAT'
  END AS trend
FROM boundaries
ORDER BY carrier_code;

\echo --- TLS session ---
SELECT
  ssl,
  version AS tls_version,
  cipher,
  bits
FROM pg_stat_ssl
WHERE pid = pg_backend_pid();

\echo --- Read-only role privileges ---
SELECT
  (SELECT NOT rolcanlogin
     FROM pg_roles
    WHERE rolname = 'hmm_federation_reader') AS no_login,
  has_schema_privilege('hmm_federation_reader', 'hmm_demo', 'USAGE') AS schema_usage,
  has_schema_privilege('hmm_federation_reader', 'hmm_demo', 'CREATE') AS schema_create,
  has_table_privilege(
    'hmm_federation_reader',
    'hmm_demo.carrier_monthly_performance',
    'SELECT'
  ) AS can_select,
  has_table_privilege(
    'hmm_federation_reader',
    'hmm_demo.carrier_monthly_performance',
    'INSERT'
  ) AS can_insert;

\echo === HMM carrier performance demo: verification complete ===
