-- 05_alerts.sql: table for alerts/warnings
CREATE TABLE IF NOT EXISTS alerts (
    id          BIGSERIAL PRIMARY KEY,
    alert_type  TEXT        NOT NULL,
    station_id  VARCHAR(50) NOT NULL,
    level       VARCHAR(10) NOT NULL CHECK (level IN ('yellow', 'red')),
    issued_at   TIMESTAMPTZ NOT NULL,
    message     TEXT,
    sms_phone   TEXT,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- One record per alert event (no SMS stored)
CREATE UNIQUE INDEX IF NOT EXISTS alerts_uniq_event
    ON alerts (alert_type, station_id, issued_at, level)
    WHERE sms_phone IS NULL;

-- One record per phone recipient
CREATE UNIQUE INDEX IF NOT EXISTS alerts_uniq_phone
    ON alerts (alert_type, station_id, issued_at, level, sms_phone)
    WHERE sms_phone IS NOT NULL;

CREATE INDEX IF NOT EXISTS alerts_station_idx ON alerts (station_id);
