-- Migration 001: user_progress + writing_submissions tables with RLS
-- Run in Supabase Dashboard → SQL Editor (after schema.sql)

-- ============================================================
-- Test results + vocab progress
-- ============================================================
CREATE TABLE IF NOT EXISTS user_progress (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id     UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  type        TEXT NOT NULL CHECK (type IN ('test', 'vocab')),
  data        JSONB NOT NULL,
  created_at  TIMESTAMPTZ DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_user_progress_user_id ON user_progress(user_id);
CREATE INDEX IF NOT EXISTS idx_user_progress_type   ON user_progress(user_id, type);

-- ============================================================
-- Writing submissions with AI feedback
-- ============================================================
CREATE TABLE IF NOT EXISTS writing_submissions (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id     UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  content     TEXT NOT NULL,
  feedback    JSONB NOT NULL,
  created_at  TIMESTAMPTZ DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_writing_submissions_user_id ON writing_submissions(user_id);

-- ============================================================
-- Row Level Security
-- ============================================================
ALTER TABLE user_progress     ENABLE ROW LEVEL SECURITY;
ALTER TABLE writing_submissions ENABLE ROW LEVEL SECURITY;

-- user_progress: authenticated users own their rows
CREATE POLICY "Users can insert own progress"
  ON user_progress FOR INSERT
  WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can read own progress"
  ON user_progress FOR SELECT
  USING (auth.uid() = user_id);

-- writing_submissions: authenticated users own their rows
CREATE POLICY "Users can insert own submissions"
  ON writing_submissions FOR INSERT
  WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can read own submissions"
  ON writing_submissions FOR SELECT
  USING (auth.uid() = user_id);
