-- +mixmaker Up
ALTER TABLE events DROP CONSTRAINT IF EXISTS events_state_check;
ALTER TABLE events ADD CONSTRAINT events_state_check CHECK (state IN (
    'RegistrationOpen', 'RegistrationClosed', 'Balancing',
    'RostersDraft', 'RostersConfirmed', 'BracketDraft', 'Live', 'Completed', 'Cancelled'
));

ALTER TABLE tournaments ADD COLUMN IF NOT EXISTS version integer NOT NULL DEFAULT 0;

CREATE TABLE IF NOT EXISTS event_bracket_drafts (
    event_id text PRIMARY KEY REFERENCES events(id) ON DELETE CASCADE,
    body jsonb NOT NULL,
    version integer NOT NULL DEFAULT 0,
    confirmed boolean NOT NULL DEFAULT false,
    updated_at timestamptz NOT NULL DEFAULT now()
);

-- +mixmaker Down
DROP TABLE IF EXISTS event_bracket_drafts;
ALTER TABLE tournaments DROP COLUMN IF EXISTS version;
UPDATE events SET state = 'RostersConfirmed' WHERE state = 'BracketDraft';
ALTER TABLE events DROP CONSTRAINT IF EXISTS events_state_check;
ALTER TABLE events ADD CONSTRAINT events_state_check CHECK (state IN (
    'RegistrationOpen', 'RegistrationClosed', 'Balancing',
    'RostersDraft', 'RostersConfirmed', 'Live', 'Completed', 'Cancelled'
));
