-- Advanced voting methods support

-- Add voting method enum type
DO $$ BEGIN
    CREATE TYPE voting_method_type AS ENUM ('approval', 'ranked_choice', 'quadratic', 'star');
EXCEPTION
    WHEN duplicate_object THEN null;
END $$;

-- Ranked votes table for ranked choice voting
CREATE TABLE IF NOT EXISTS ranked_votes (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    proposal_id UUID NOT NULL REFERENCES proposals(id) ON DELETE CASCADE,
    voter_id UUID NOT NULL REFERENCES voting_identities(id),
    option_id UUID NOT NULL REFERENCES proposal_options(id) ON DELETE CASCADE,
    rank INTEGER NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(proposal_id, voter_id, option_id),
    UNIQUE(proposal_id, voter_id, rank)
);

-- Quadratic votes table (stores credit allocation)
CREATE TABLE IF NOT EXISTS quadratic_votes (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    proposal_id UUID NOT NULL REFERENCES proposals(id) ON DELETE CASCADE,
    voter_id UUID NOT NULL REFERENCES voting_identities(id),
    option_id UUID NOT NULL REFERENCES proposal_options(id) ON DELETE CASCADE,
    credits INTEGER NOT NULL CHECK (credits >= 0),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(proposal_id, voter_id, option_id)
);

-- Star rating votes (0-5 stars per option)
CREATE TABLE IF NOT EXISTS star_votes (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    proposal_id UUID NOT NULL REFERENCES proposals(id) ON DELETE CASCADE,
    voter_id UUID NOT NULL REFERENCES voting_identities(id),
    option_id UUID NOT NULL REFERENCES proposal_options(id) ON DELETE CASCADE,
    stars INTEGER NOT NULL CHECK (stars >= 0 AND stars <= 5),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(proposal_id, voter_id, option_id)
);

CREATE INDEX IF NOT EXISTS idx_ranked_votes_proposal ON ranked_votes(proposal_id);
CREATE INDEX IF NOT EXISTS idx_quadratic_votes_proposal ON quadratic_votes(proposal_id);
CREATE INDEX IF NOT EXISTS idx_star_votes_proposal ON star_votes(proposal_id);
