-- 038: Telecom Entity tracking — multi-entity support
--
-- Links customers to their telecom entities (each with FRN, 499 Filer ID, etc.)
-- A single customer can manage multiple entities.
-- Compliance checks and 499-A filings are scoped per entity.

CREATE TABLE IF NOT EXISTS telecom_entities (
    id              SERIAL PRIMARY KEY,
    customer_id     INTEGER REFERENCES customers(id),
    -- Jurisdiction
    jurisdiction    TEXT NOT NULL DEFAULT 'FCC'
                    CHECK (jurisdiction IN ('FCC', 'CRTC')),
    -- FCC identifiers (US entities)
    frn             TEXT,                           -- 10-digit FCC Registration Number
    filer_id_499    TEXT,                           -- USAC 499 Filer ID
    -- CRTC identifiers (Canadian entities)
    incorporation_number TEXT,                      -- BC/ON provincial corporation number
    incorporation_province TEXT,                    -- BC or ON
    crtc_registration_number TEXT,                  -- CRTC carrier registration ID
    -- Entity info
    legal_name      TEXT NOT NULL,
    dba_name        TEXT,
    ein             TEXT,                           -- EIN (US) or BN (Canada)
    -- Classification (from 499-A questionnaire — FCC entities)
    filer_type      TEXT,                           -- interconnected_voip, non_interconnected_voip, clec, etc.
    infra_type      TEXT,                           -- facilities, reseller, both
    is_deminimis    BOOLEAN DEFAULT FALSE,
    is_lire         BOOLEAN DEFAULT FALSE,
    service_categories TEXT[],                      -- array of category slugs
    -- Contact
    contact_name    TEXT,
    contact_email   TEXT,
    contact_phone   TEXT,
    ceo_name        TEXT,
    ceo_title       TEXT,
    -- Address
    address_street  TEXT,
    address_city    TEXT,
    address_state   TEXT,
    address_zip     TEXT,
    -- Revenue snapshot (from last 499-A)
    last_filing_year    INTEGER,
    total_revenue_cents  BIGINT DEFAULT 0,
    interstate_pct       NUMERIC(5,2) DEFAULT 0,
    international_pct    NUMERIC(5,2) DEFAULT 0,
    -- Status
    active          BOOLEAN DEFAULT TRUE,
    notes           TEXT,
    -- ERPNext link
    erpnext_customer TEXT,                          -- ERPNext Customer docname
    -- Metadata
    created_at      TIMESTAMPTZ DEFAULT NOW(),
    updated_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_telecom_entities_customer ON telecom_entities(customer_id);
CREATE INDEX IF NOT EXISTS idx_telecom_entities_frn ON telecom_entities(frn) WHERE frn IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_telecom_entities_filer ON telecom_entities(filer_id_499) WHERE filer_id_499 IS NOT NULL;

-- Add entity_id to compliance-related tables
ALTER TABLE canada_crtc_orders ADD COLUMN IF NOT EXISTS telecom_entity_id INTEGER REFERENCES telecom_entities(id);
