-- ─────────────────────────────────────────────────────────────────
-- FASE 4: Preço Dinâmico
-- ─────────────────────────────────────────────────────────────────

CREATE TABLE IF NOT EXISTS raffle_price_rules (
  id            SERIAL PRIMARY KEY,
  raffle_id     INTEGER NOT NULL REFERENCES raffles(id) ON DELETE CASCADE,
  rule_type     TEXT NOT NULL CHECK (rule_type IN ('fixed', 'time_range')),
  price         NUMERIC(10,2) NOT NULL,
  start_at      TIMESTAMPTZ, -- Usado apenas se rule_type = 'time_range'
  end_at        TIMESTAMPTZ, -- Usado apenas se rule_type = 'time_range'
  priority      INTEGER DEFAULT 0,
  created_at    TIMESTAMPTZ DEFAULT NOW(),
  active        INTEGER DEFAULT 1
);

CREATE TABLE IF NOT EXISTS price_logs (
  id            SERIAL PRIMARY KEY,
  raffle_id     INTEGER NOT NULL REFERENCES raffles(id) ON DELETE CASCADE,
  order_id      TEXT REFERENCES orders(id) ON DELETE SET NULL,
  user_cpf      TEXT,
  price_applied NUMERIC(10,2) NOT NULL,
  rule_id       INTEGER REFERENCES raffle_price_rules(id) ON DELETE SET NULL,
  created_at    TIMESTAMPTZ DEFAULT NOW()
);
