-- M7 recurring-scans: singleton table holding the operator's schedule
-- config. mode is the discriminator: 'off' / 'interval' / 'daily' / 'weekly'.
-- Per-mode fields are populated only when their mode is selected; others
-- stay NULL. weekly_day uses ISO 8601: 1=Monday … 7=Sunday.
CREATE TABLE scan_schedule (
    id             boolean PRIMARY KEY DEFAULT true,
    mode           text NOT NULL DEFAULT 'off',
    interval_hours int,
    time_of_day    text,
    weekly_day     int,
    updated_at     timestamptz NOT NULL DEFAULT now(),
    CONSTRAINT scan_schedule_singleton CHECK (id = true),
    CONSTRAINT scan_schedule_mode_check
        CHECK (mode IN ('off', 'interval', 'daily', 'weekly')),
    CONSTRAINT scan_schedule_interval_check
        CHECK (mode != 'interval' OR (interval_hours IS NOT NULL AND interval_hours > 0)),
    CONSTRAINT scan_schedule_daily_check
        CHECK (mode != 'daily' OR time_of_day IS NOT NULL),
    CONSTRAINT scan_schedule_weekly_check
        CHECK (mode != 'weekly' OR (time_of_day IS NOT NULL AND weekly_day IS NOT NULL AND weekly_day BETWEEN 1 AND 7))
);

INSERT INTO scan_schedule (id) VALUES (true);
