-- ============================================================
-- Step 6: verify the local federation Views.
-- Expected: carrier/performance/latest = 8/144/8.
-- Redmine: #730
-- ============================================================

DECLARE
  v_carrier_count     PLS_INTEGER;
  v_performance_count PLS_INTEGER;
  v_latest_count      PLS_INTEGER;
  v_risk_count        PLS_INTEGER;
BEGIN
  SELECT COUNT(*) INTO v_carrier_count
  FROM HMM_RDS_CARRIERS_V;

  SELECT COUNT(*) INTO v_performance_count
  FROM HMM_RDS_CARRIER_PERF_V;

  SELECT COUNT(*), COUNT(DISTINCT risk_level)
  INTO v_latest_count, v_risk_count
  FROM HMM_RDS_CARRIER_LATEST_V;

  IF v_carrier_count != 8 THEN
    RAISE_APPLICATION_ERROR(
      -20001,
      'Expected 8 carriers, found ' || v_carrier_count
    );
  END IF;

  IF v_performance_count != 144 THEN
    RAISE_APPLICATION_ERROR(
      -20002,
      'Expected 144 performance rows, found ' || v_performance_count
    );
  END IF;

  IF v_latest_count != 8 OR v_risk_count != 3 THEN
    RAISE_APPLICATION_ERROR(
      -20003,
      'Expected 8 latest rows and 3 risk levels, found '
      || v_latest_count || ' rows and ' || v_risk_count || ' levels'
    );
  END IF;
END;
/

SELECT
  (SELECT COUNT(*) FROM HMM_RDS_CARRIERS_V) AS carrier_count,
  (SELECT COUNT(*) FROM HMM_RDS_CARRIER_PERF_V) AS performance_count,
  (SELECT COUNT(*) FROM HMM_RDS_CARRIER_LATEST_V) AS latest_count
FROM dual;

SELECT
  MIN(performance_month) AS first_month,
  MAX(performance_month) AS latest_month,
  COUNT(DISTINCT carrier_code) AS carrier_count
FROM HMM_RDS_CARRIER_PERF_V;

SELECT risk_level, COUNT(*) AS carrier_count
FROM HMM_RDS_CARRIER_LATEST_V
GROUP BY risk_level
ORDER BY risk_level;

SELECT
  carrier_code,
  carrier_name,
  performance_month,
  shipped_teu,
  revenue_usd,
  gross_margin_usd,
  schedule_reliability_pct,
  claim_rate_pct,
  risk_level
FROM HMM_RDS_CARRIER_LATEST_V
ORDER BY carrier_code;

SELECT
  table_name,
  comments
FROM user_tab_comments
WHERE table_name IN (
  'HMM_RDS_CARRIERS_V',
  'HMM_RDS_CARRIER_PERF_V',
  'HMM_RDS_CARRIER_LATEST_V'
)
ORDER BY table_name;
