-- Voting System Schema

-- Proposal status enum
CREATE TYPE proposal_status AS ENUM ('draft', 'discussion', 'voting', 'closed', 'archived');

-- Proposals table
CREATE TABLE proposals (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    community_id UUID NOT NULL REFERENCES communities(id) ON DELETE CASCADE,
    author_id UUID NOT NULL REFERENCES users(id),
    title VARCHAR(255) NOT NULL,
    description TEXT NOT NULL,
    status proposal_status NOT NULL DEFAULT 'draft',
    voting_method VARCHAR(50) NOT NULL DEFAULT 'approval',
    voting_starts_at TIMESTAMPTZ,
    voting_ends_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Proposal options (for voting)
CREATE TABLE proposal_options (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    proposal_id UUID NOT NULL REFERENCES proposals(id) ON DELETE CASCADE,
    label VARCHAR(255) NOT NULL,
    description TEXT,
    sort_order INT NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Votes table (approval voting - can vote for multiple options)
CREATE TABLE votes (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    proposal_id UUID NOT NULL REFERENCES proposals(id) ON DELETE CASCADE,
    option_id UUID NOT NULL REFERENCES proposal_options(id) ON DELETE CASCADE,
    voter_id UUID NOT NULL REFERENCES voting_identities(id),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(proposal_id, option_id, voter_id)
);

-- Indexes
CREATE INDEX idx_proposals_community ON proposals(community_id);
CREATE INDEX idx_proposals_status ON proposals(status);
CREATE INDEX idx_proposal_options_proposal ON proposal_options(proposal_id);
CREATE INDEX idx_votes_proposal ON votes(proposal_id);
CREATE INDEX idx_votes_option ON votes(option_id);

-- Updated_at trigger
CREATE TRIGGER proposals_updated_at BEFORE UPDATE ON proposals
    FOR EACH ROW EXECUTE FUNCTION update_updated_at();
