-- Migration: Domain Submission Feature
-- Adds status + postId to user_custom_domains
-- Adds domain_submissions and domain_votes tables

SET search_path TO rebreak;

-- 1. Add status + postId to existing custom domains
ALTER TABLE user_custom_domains
  ADD COLUMN IF NOT EXISTS status  TEXT NOT NULL DEFAULT 'active',
  ADD COLUMN IF NOT EXISTS post_id UUID;

-- 2. Domain submissions table (admin + community review)
CREATE TABLE IF NOT EXISTS domain_submissions (
  id               UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id          UUID NOT NULL,
  domain           TEXT NOT NULL,
  custom_domain_id UUID NOT NULL UNIQUE REFERENCES user_custom_domains(id) ON DELETE CASCADE,
  post_id          UUID,
  status           TEXT NOT NULL DEFAULT 'pending',
  yes_votes        INT  NOT NULL DEFAULT 0,
  no_votes         INT  NOT NULL DEFAULT 0,
  review_note      TEXT,
  created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
  reviewed_at      TIMESTAMPTZ
);

-- 3. Domain votes table (one vote per user per submission)
CREATE TABLE IF NOT EXISTS domain_votes (
  user_id       UUID NOT NULL,
  submission_id UUID NOT NULL REFERENCES domain_submissions(id) ON DELETE CASCADE,
  vote          TEXT NOT NULL, -- 'yes' | 'no'
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (user_id, submission_id)
);

CREATE INDEX IF NOT EXISTS idx_domain_submissions_status  ON domain_submissions(status);
CREATE INDEX IF NOT EXISTS idx_domain_submissions_user_id ON domain_submissions(user_id);
CREATE INDEX IF NOT EXISTS idx_domain_votes_submission    ON domain_votes(submission_id);
