-- 043: Carrier classification for FCC compliance checkup
--
-- Adds carrier type classification fields to telecom_entities.
-- Used to determine proper RMD letter template, CPNI cert format,
-- and 499-A filing preparation based on carrier category.

-- Primary carrier category (how the provider registers with FCC)
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS carrier_category TEXT
    CHECK (carrier_category IN (
        'interconnected_voip',
        'non_interconnected_voip',
        'clec',
        'ixc',
        'cmrs',
        'other'
    ));

-- Operational role flags (not mutually exclusive)
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS is_wholesale BOOLEAN DEFAULT FALSE;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS is_gateway_provider BOOLEAN DEFAULT FALSE;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS is_international_only BOOLEAN DEFAULT FALSE;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS uses_ucaas_provider BOOLEAN DEFAULT FALSE;

-- Type-specific metadata (JSONB to avoid endless nullable columns)
-- UCaaS:     {"ucaas_provider": "RingCentral", "ucaas_provider_frn": "0012345678"}
-- Gateway:   {"gateway_countries": ["Mexico","India"], "gateway_type": "international"}
-- Wholesale: {"wholesale_customer_types": ["clec","voip"], "downstream_count_approx": 50}
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS carrier_metadata JSONB DEFAULT '{}';

-- STIR/SHAKEN specifics (needed for RMD letter sections)
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS stir_shaken_status TEXT
    CHECK (stir_shaken_status IN (
        'complete_implementation',
        'partial_implementation',
        'robocall_mitigation_only',
        'exempt_small_carrier',
        'not_applicable'
    ));
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS stir_shaken_cert_authority TEXT;

-- Upstream provider (for resellers and UCaaS-based carriers)
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS upstream_provider_name TEXT;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS upstream_provider_frn TEXT;

-- RMD letter generation tracking
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS rmd_letter_minio_path TEXT;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS rmd_letter_generated_at TIMESTAMPTZ;

-- Last compliance checkup timestamp
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS last_compliance_checkup TIMESTAMPTZ;

-- Index for filtering by carrier category
CREATE INDEX IF NOT EXISTS idx_telecom_entities_carrier_category
    ON telecom_entities(carrier_category) WHERE carrier_category IS NOT NULL;
