-- Reschedule proposals: tracks GM-initiated time change requests
-- Status flow: AwaitingTime → Voting → Approved/Rejected

CREATE TABLE reschedule_proposals (
    id                  UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id          UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
    proposed_at         TIMESTAMPTZ,                 -- new proposed time (NULL while AwaitingTime)
    proposed_by         BIGINT NOT NULL,              -- GM's telegram_id
    status              VARCHAR(50) NOT NULL DEFAULT 'AwaitingTime'
                        CHECK (status IN ('AwaitingTime', 'Voting', 'Approved', 'Rejected')),
    vote_message_id     INTEGER,                      -- message ID of the voting message in chat
    vote_chat_id        BIGINT,                       -- chat where voting takes place
    created_at          TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Only one active proposal per session at a time
CREATE UNIQUE INDEX ix_reschedule_active ON reschedule_proposals (session_id)
    WHERE status IN ('AwaitingTime', 'Voting');

CREATE TABLE reschedule_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,
    vote            VARCHAR(10) NOT NULL CHECK (vote IN ('yes', 'no')),
    voted_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (proposal_id, player_id)
);
