-- 047: Carrier filing state tracking + checkup recommendations
--
-- Part A: Record when each filing was last submitted to the FCC so that
-- the automated remediation handlers can be idempotent (skip or abbreviate
-- if a filing is already on record for the current cycle). Re-running the
-- compliance checkup reads these timestamps and flips deficiencies green
-- once the corresponding filing completes.
--
-- Part B: Persist the list of recommended follow-up services produced by
-- the FCC Compliance Checkup so the delivery email / portal can surface
-- one-click upsell links per order.

-- ── Part A: filing state on the carrier ──────────────────────────────────
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS rmd_last_cert_date TIMESTAMPTZ;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS cpni_last_cert_date TIMESTAMPTZ;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS bdc_last_filing_date TIMESTAMPTZ;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS stir_shaken_cert_issued_at TIMESTAMPTZ;

-- Confirmation numbers returned by the FCC/USAC portals (captured from the
-- confirmation page screenshot during automated submission)
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS rmd_confirmation_number TEXT;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS cpni_confirmation_number TEXT;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS form_499a_confirmation_number TEXT;
ALTER TABLE telecom_entities ADD COLUMN IF NOT EXISTS bdc_confirmation_number TEXT;

-- ── Part B: recommended follow-up services from the checkup ──────────────
ALTER TABLE compliance_orders ADD COLUMN IF NOT EXISTS recommended_slugs TEXT[] DEFAULT '{}';

-- ── Part C: portal onboarding flag ──────────────────────────────────────
-- True on orders where the checkout flow created a brand-new ERPNext
-- Website User for the customer. The success page reads this flag to
-- decide whether to render the set-password form, and the delivery
-- worker reads it to decide whether to include a magic-link fallback.
ALTER TABLE compliance_orders   ADD COLUMN IF NOT EXISTS portal_user_created BOOLEAN DEFAULT FALSE;
ALTER TABLE canada_crtc_orders  ADD COLUMN IF NOT EXISTS portal_user_created BOOLEAN DEFAULT FALSE;
ALTER TABLE formation_orders    ADD COLUMN IF NOT EXISTS portal_user_created BOOLEAN DEFAULT FALSE;

-- Index to find carriers that are overdue on any filing type (used by the
-- renewal worker and by admin dashboards)
CREATE INDEX IF NOT EXISTS idx_telecom_entities_rmd_last_cert
    ON telecom_entities(rmd_last_cert_date) WHERE rmd_last_cert_date IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_telecom_entities_cpni_last_cert
    ON telecom_entities(cpni_last_cert_date) WHERE cpni_last_cert_date IS NOT NULL;
