-- Recorder schedules
--
-- Lets operators schedule a recorder to start at a future time and stop
-- after a duration. The scheduler tick loop in mam-api (src/scheduler.js)
-- watches this table every 15s and triggers the existing /recorders/:id
-- start + stop endpoints when each schedule's window opens or closes.
--
-- recurrence: 'none' (one-shot) or 'daily' for the MVP. When a 'daily'
-- schedule completes, the tick loop clones it forward by 24h.

CREATE TABLE IF NOT EXISTS recorder_schedules (
  id              UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
  name            TEXT        NOT NULL,
  recorder_id     UUID        NOT NULL REFERENCES recorders(id) ON DELETE CASCADE,
  start_at        TIMESTAMPTZ NOT NULL,
  end_at          TIMESTAMPTZ NOT NULL,
  recurrence      TEXT        NOT NULL DEFAULT 'none',
  status          TEXT        NOT NULL DEFAULT 'pending',
  last_asset_id   UUID,
  error_message   TEXT,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  CHECK (end_at > start_at),
  CHECK (recurrence IN ('none','daily','weekly')),
  CHECK (status IN ('pending','running','completed','failed','cancelled'))
);

CREATE INDEX IF NOT EXISTS idx_recorder_schedules_status_start
  ON recorder_schedules (status, start_at);

CREATE INDEX IF NOT EXISTS idx_recorder_schedules_recorder
  ON recorder_schedules (recorder_id);
