-- 073_state_puc_registrations.sql
--
-- Per-state PUC/PSC registration tracking, one row per state per order.
-- Follows the foreign_qualification_registrations pattern from migration 066.

BEGIN;

CREATE TABLE IF NOT EXISTS state_puc_registrations (
    id                      BIGSERIAL PRIMARY KEY,

    -- Parent order
    compliance_order_id     INTEGER REFERENCES compliance_orders(id) ON DELETE SET NULL,
    order_number            TEXT NOT NULL,

    -- Linked carrier
    telecom_entity_id       INTEGER,
    state_code              CHAR(2) NOT NULL,
    registration_type       TEXT NOT NULL,  -- 'voip','broadband','clec','bundle'
    entity_legal_name       TEXT NOT NULL,
    frn                     TEXT,

    -- Provider classification (affects requirements in many states)
    provider_type           TEXT CHECK (provider_type IN (
        'facilities_based', 'reseller', 'over_the_top', 'hybrid'
    )),

    -- Status pipeline
    status TEXT NOT NULL DEFAULT 'received' CHECK (status IN (
        'received',          -- paid, queued
        'docs_pending',      -- waiting on supporting documents
        'bond_pending',      -- waiting on surety bond procurement
        'filing',            -- preparing/submitting to state PUC
        'admin_review',      -- manual step needed
        'submitted',         -- filed, awaiting state approval
        'approved',          -- certificate/registration issued
        'rejected',
        'cancelled'
    )),

    -- Fees (cents)
    state_fee_cents         INTEGER NOT NULL DEFAULT 0,
    bond_amount_cents       INTEGER NOT NULL DEFAULT 0,
    service_fee_cents       INTEGER NOT NULL DEFAULT 0,
    retail_total_cents      INTEGER NOT NULL DEFAULT 0,

    -- Registration details
    puc_registration_number TEXT,
    puc_certificate_number  TEXT,
    filed_at                TIMESTAMPTZ,
    approved_at             TIMESTAMPTZ,
    certificate_minio_path  TEXT,

    -- Bond info
    bond_company            TEXT,
    bond_policy_number      TEXT,
    bond_expiration_date    DATE,

    -- Tracking
    attempt_count           INTEGER NOT NULL DEFAULT 0,
    last_error              TEXT,
    admin_todo_id           INTEGER,
    notes                   TEXT,
    created_at              TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at              TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    UNIQUE (telecom_entity_id, state_code, order_number)
);

CREATE INDEX IF NOT EXISTS idx_puc_reg_order_number
  ON state_puc_registrations(order_number);
CREATE INDEX IF NOT EXISTS idx_puc_reg_state_code
  ON state_puc_registrations(state_code);
CREATE INDEX IF NOT EXISTS idx_puc_reg_status
  ON state_puc_registrations(status)
  WHERE status NOT IN ('approved','cancelled','rejected');
CREATE INDEX IF NOT EXISTS idx_puc_reg_telecom_entity
  ON state_puc_registrations(telecom_entity_id)
  WHERE telecom_entity_id IS NOT NULL;

-- Updated_at trigger
CREATE OR REPLACE FUNCTION set_updated_at_puc_reg() RETURNS trigger AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_puc_reg_updated_at ON state_puc_registrations;
CREATE TRIGGER trg_puc_reg_updated_at
  BEFORE UPDATE ON state_puc_registrations
  FOR EACH ROW EXECUTE FUNCTION set_updated_at_puc_reg();

-- Admin pipeline view
CREATE OR REPLACE VIEW v_puc_registrations_pipeline AS
SELECT
  pr.id,
  pr.order_number,
  pr.entity_legal_name,
  pr.state_code,
  j.name            AS state_name,
  pr.registration_type,
  pr.provider_type,
  pr.status,
  pr.state_fee_cents,
  pr.bond_amount_cents,
  pr.retail_total_cents,
  pr.filed_at,
  pr.approved_at,
  pr.attempt_count,
  pr.last_error,
  pr.created_at
FROM state_puc_registrations pr
LEFT JOIN jurisdictions j ON j.code = pr.state_code
ORDER BY pr.created_at DESC;

COMMIT;
