-- 002_schedules.sql — timed / event-driven actions on instances.
--
-- For the MVP only cron triggers are supported; trigger_kind leaves room
-- for future 'event' / 'composite' without a schema change.
--
-- action is JSONB so new action types (webhook, exec, etc.) can be added
-- without migrations. The controller's scheduler engine validates shape
-- at dispatch time.
--
-- last_fired_at / last_status let the UI show whether a schedule is
-- actually doing what it says.

CREATE TABLE schedules (
    id              TEXT PRIMARY KEY,
    instance_id     TEXT NOT NULL,
    description     TEXT NOT NULL DEFAULT '',
    trigger_kind    TEXT NOT NULL DEFAULT 'cron',
    cron_spec       TEXT NOT NULL,
    action          JSONB NOT NULL,
    enabled         BOOLEAN NOT NULL DEFAULT TRUE,
    last_fired_at   TIMESTAMPTZ,
    last_status     TEXT,
    last_detail     TEXT,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_schedules_instance ON schedules(instance_id);
CREATE INDEX idx_schedules_enabled  ON schedules(enabled) WHERE enabled = TRUE;
