-- 052: Fields for the four new FCC filings + intake validation
--
-- Adds the telecom_entities columns the new handlers (CORES/FRN, 499 Initial,
-- CALEA SSI, Foreign Carrier Affiliation) persist to, plus a validated flag
-- on compliance_orders for the /validate dry-run endpoint.

-- ── CORES / FRN credentials ──────────────────────────────────────────────
-- We register carriers in FCC CORES on their behalf; store the assigned
-- username + the bcrypt hash of the password we set during registration
-- so a customer calling in later can verify identity without us holding
-- plaintext. Plaintext is delivered to the customer ONCE in a credential
-- packet PDF.
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS cores_username TEXT;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS cores_password_hash TEXT;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS cores_registered_at TIMESTAMPTZ;

-- ── CALEA SSI plan state ─────────────────────────────────────────────────
-- 47 USC 229 / 47 CFR 1.20003 — every carrier must maintain an SSI plan.
-- The plan isn't filed with the FCC (kept internally + provided to DOJ on
-- subpoena), so all state is local. Annual review required.
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS calea_ssi_generated_at TIMESTAMPTZ;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS calea_ssi_reviewer_name TEXT;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS calea_ssi_next_review_date DATE;

-- ── Foreign carrier affiliations (47 CFR § 63.11) ────────────────────────
-- Array of notification records — one carrier may have multiple foreign
-- affiliations over time. Each element:
--   { "foreign_carrier_legal_name": "...", "country": "ISO-2",
--     "ownership_pct": <number>, "affected_routes": ["CA","MX"],
--     "affiliation_date": "YYYY-MM-DD", "filed_at": "ISO-8601",
--     "ecfs_confirmation": "2026XXXXXXXXX" }
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS foreign_affiliations JSONB DEFAULT '[]'::jsonb;

-- ── Pre-payment validation flag ──────────────────────────────────────────
-- Flipped TRUE by POST /api/v1/compliance-orders/:order_number/validate
-- once every required intake_data field is present. Stripe checkout
-- refuses to create a session when FALSE (UI enforces this client-side
-- too, but the API is the last line of defense).
ALTER TABLE compliance_orders ADD COLUMN IF NOT EXISTS intake_data_validated BOOLEAN DEFAULT FALSE;
ALTER TABLE compliance_orders ADD COLUMN IF NOT EXISTS validation_errors JSONB;

-- ── Indexes ──────────────────────────────────────────────────────────────
CREATE INDEX IF NOT EXISTS idx_telecom_entities_cores_username
    ON telecom_entities(cores_username)
    WHERE cores_username IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_telecom_entities_calea_next_review
    ON telecom_entities(calea_ssi_next_review_date)
    WHERE calea_ssi_next_review_date IS NOT NULL;
