-- Migration 094: Scheduled Messages tables

CREATE TABLE IF NOT EXISTS scheduled_message_rules (
  id                        UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name                      TEXT NOT NULL,
  message_type              TEXT NOT NULL,
  -- message_type values: event_summary | birthday_list | dienstjubilaeen |
  --                      fahrzeug_status | fahrzeug_event | bestellungen
  trigger_mode              TEXT NOT NULL,
  -- trigger_mode values: day_of_week | days_before_month_start | event
  day_of_week               INT,           -- 0-6, used when trigger_mode = day_of_week
  send_time                 TIME,          -- used when trigger_mode = day_of_week
  days_before_month_start   INT,           -- used when trigger_mode = days_before_month_start
  window_mode               TEXT,          -- rolling | calendar_month | NULL for event types
  window_days               INT,           -- used when window_mode = rolling
  target_room_token         TEXT NOT NULL,
  target_room_name          TEXT,
  template                  TEXT NOT NULL,
  extra_config              JSONB,         -- e.g. {"min_days_overdue": 14} for bestellungen
  subscribable              BOOLEAN NOT NULL DEFAULT FALSE,
  allowed_groups            TEXT[],        -- Authentik group names allowed to subscribe
  last_sent_at              DATE,
  active                    BOOLEAN NOT NULL DEFAULT TRUE,
  created_at                TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  created_by                UUID REFERENCES users(id) ON DELETE SET NULL
);

CREATE TABLE IF NOT EXISTS scheduled_message_subscriptions (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  rule_id     UUID NOT NULL REFERENCES scheduled_message_rules(id) ON DELETE CASCADE,
  user_id     UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  room_token  TEXT NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  UNIQUE (rule_id, user_id)
);

CREATE INDEX IF NOT EXISTS idx_smr_active_trigger
  ON scheduled_message_rules(active, trigger_mode);
CREATE INDEX IF NOT EXISTS idx_sms_rule_id
  ON scheduled_message_subscriptions(rule_id);
CREATE INDEX IF NOT EXISTS idx_sms_user_id
  ON scheduled_message_subscriptions(user_id);
