-- =============================================
-- STORYBOARD HISTORY TABLE
-- Run AFTER schema.sql
-- =============================================

CREATE TABLE IF NOT EXISTS storyboard_history (
  id              UUID        PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id         UUID        NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
  source_url      TEXT        NOT NULL,
  source_platform TEXT        NOT NULL DEFAULT 'website',
  source_title    TEXT,
  style           TEXT        NOT NULL DEFAULT 'cinematic'
                  CHECK (style IN ('cinematic','documentary','social_media','ugc','explainer','emotional','humorous')),
  length          TEXT        NOT NULL DEFAULT 'medium'
                  CHECK (length IN ('short','medium','long','custom')),
  language        TEXT        NOT NULL DEFAULT 'id'
                  CHECK (language IN ('id','en')),
  output          JSONB       NOT NULL,
  is_favorite     BOOLEAN     NOT NULL DEFAULT FALSE,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- RLS
ALTER TABLE storyboard_history ENABLE ROW LEVEL SECURITY;

CREATE POLICY "storyboard: select own"
  ON storyboard_history FOR SELECT USING (auth.uid() = user_id);
CREATE POLICY "storyboard: insert own"
  ON storyboard_history FOR INSERT WITH CHECK (auth.uid() = user_id);
CREATE POLICY "storyboard: update own"
  ON storyboard_history FOR UPDATE USING (auth.uid() = user_id);
CREATE POLICY "storyboard: delete own"
  ON storyboard_history FOR DELETE USING (auth.uid() = user_id);

-- Admin can view all
CREATE POLICY "storyboard: admin view all"
  ON storyboard_history FOR SELECT USING (is_admin());

-- Indexes
CREATE INDEX IF NOT EXISTS idx_storyboard_user_id    ON storyboard_history(user_id);
CREATE INDEX IF NOT EXISTS idx_storyboard_created_at ON storyboard_history(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_storyboard_platform   ON storyboard_history(source_platform);
CREATE INDEX IF NOT EXISTS idx_storyboard_favorite   ON storyboard_history(is_favorite) WHERE is_favorite = TRUE;
