-- 049: USF quarterly contribution factor tracking
--
-- USAC publishes the federal Universal Service Fund contribution factor
-- (and the associated circularity factor) once per quarter, at
-- https://www.usac.org/service-providers/making-payments/contribution-factors/.
-- The FCC Public Notice typically drops ~14 days before the quarter
-- starts, though the posting date isn't deterministic.
--
-- The usf_factor_monitor worker fetches that page daily, upserts each
-- quarter's factor row here, and when a NEW quarter appears sends a
-- one-shot notification email to every client with an FCC carrier so
-- they can update their customer bill surcharges.

CREATE TABLE IF NOT EXISTS usf_contribution_factors (
    id                 SERIAL PRIMARY KEY,
    year               INT  NOT NULL,
    quarter            INT  NOT NULL CHECK (quarter BETWEEN 1 AND 4),
    effective_start    DATE NOT NULL,
    effective_end      DATE NOT NULL,
    factor_pct         NUMERIC(6, 4) NOT NULL,
    circularity_pct    NUMERIC(6, 4),
    fcc_public_notice  TEXT,
    first_seen_at      TIMESTAMPTZ DEFAULT NOW(),
    notified_at        TIMESTAMPTZ,
    notification_count INT DEFAULT 0,
    UNIQUE (year, quarter)
);

CREATE INDEX IF NOT EXISTS idx_usf_factors_effective_start
    ON usf_contribution_factors(effective_start);

COMMENT ON TABLE usf_contribution_factors IS
    'Quarterly FCC/USAC Universal Service Fund contribution factors. '
    'Fed daily by scripts.workers.usf_factor_monitor from the USAC site.';
COMMENT ON COLUMN usf_contribution_factors.factor_pct IS
    'Contribution factor as percentage (e.g., 37.6 for 37.6%).';
COMMENT ON COLUMN usf_contribution_factors.circularity_pct IS
    'Circularity factor — used to back out gross from net USF pass-through.';
COMMENT ON COLUMN usf_contribution_factors.notified_at IS
    'Timestamp of the one-shot client notification email. Prevents duplicate sends.';
