-- 080_carrier_operating_states.sql
--
-- Track which states a carrier operates in. Populated from:
--   - Intake forms (customer self-reports operating states)
--   - FMCSA census (phy_state as base state)
--   - Inferred from order history
--
-- Used by the DOT compliance checker to show state-specific requirements
-- and by the deficiency flagger for state-targeted campaigns.

BEGIN;

CREATE TABLE IF NOT EXISTS carrier_operating_states (
    id              SERIAL PRIMARY KEY,
    dot_number      TEXT NOT NULL,
    state_code      CHAR(2) NOT NULL,
    is_base_state   BOOLEAN NOT NULL DEFAULT FALSE,
    source          TEXT NOT NULL DEFAULT 'intake',  -- 'intake', 'census', 'inferred'
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (dot_number, state_code)
);

CREATE INDEX IF NOT EXISTS idx_carrier_ops_dot ON carrier_operating_states(dot_number);
CREATE INDEX IF NOT EXISTS idx_carrier_ops_state ON carrier_operating_states(state_code);
CREATE INDEX IF NOT EXISTS idx_carrier_ops_base ON carrier_operating_states(is_base_state) WHERE is_base_state = TRUE;

COMMIT;
