-- Multi-option reschedule voting with a deadline.

ALTER TABLE reschedule_proposals
    ADD COLUMN voting_deadline_at TIMESTAMPTZ,
    ADD COLUMN selected_option_id UUID;

CREATE TABLE reschedule_options (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    proposal_id     UUID NOT NULL REFERENCES reschedule_proposals(id) ON DELETE CASCADE,
    proposed_at     TIMESTAMPTZ NOT NULL,
    display_order   INTEGER NOT NULL CHECK (display_order BETWEEN 1 AND 3),
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (proposal_id, id),
    UNIQUE (proposal_id, display_order),
    UNIQUE (proposal_id, proposed_at)
);

CREATE TABLE reschedule_option_votes (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    proposal_id     UUID NOT NULL REFERENCES reschedule_proposals(id) ON DELETE CASCADE,
    player_id       UUID NOT NULL REFERENCES players(id) ON DELETE CASCADE,
    option_id       UUID NOT NULL,
    voted_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (proposal_id, player_id),
    FOREIGN KEY (proposal_id, option_id)
        REFERENCES reschedule_options(proposal_id, id)
        ON DELETE CASCADE
);

CREATE INDEX ix_reschedule_voting_deadline
    ON reschedule_proposals (voting_deadline_at)
    WHERE status = 'Voting';

CREATE INDEX ix_reschedule_option_votes_option
    ON reschedule_option_votes (option_id);
