-- Add optional comment to deck ratings (schema omotomo).
-- If deck_ratings doesn't exist (earlier migration not run), create the full table including comment.
DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'omotomo' AND tablename = 'deck_ratings') THEN
    CREATE TABLE omotomo.deck_ratings (
      deck_id uuid NOT NULL REFERENCES omotomo.decks(id) ON DELETE CASCADE,
      user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
      rating smallint NOT NULL CHECK (rating >= 1 AND rating <= 5),
      created_at timestamptz NOT NULL DEFAULT now(),
      comment text,
      PRIMARY KEY (deck_id, user_id)
    );
    CREATE INDEX idx_deck_ratings_deck_id ON omotomo.deck_ratings(deck_id);
    ALTER TABLE omotomo.deck_ratings ENABLE ROW LEVEL SECURITY;
    CREATE POLICY deck_ratings_select ON omotomo.deck_ratings FOR SELECT USING (true);
    CREATE POLICY deck_ratings_insert ON omotomo.deck_ratings FOR INSERT WITH CHECK (
      auth.uid() = user_id
      AND (SELECT d.owner_id FROM omotomo.decks d WHERE d.id = deck_id) IS DISTINCT FROM auth.uid()
    );
    CREATE POLICY deck_ratings_update ON omotomo.deck_ratings FOR UPDATE USING (auth.uid() = user_id) WITH CHECK (
      auth.uid() = user_id
      AND (SELECT d.owner_id FROM omotomo.decks d WHERE d.id = deck_id) IS DISTINCT FROM auth.uid()
    );
    CREATE POLICY deck_ratings_delete ON omotomo.deck_ratings FOR DELETE USING (auth.uid() = user_id);
  ELSE
    ALTER TABLE omotomo.deck_ratings ADD COLUMN IF NOT EXISTS comment text;
  END IF;
END $$;
