-- Adds multi-stage tournaments (rounds) support
-- MariaDB/MySQL compatible migration (manual execution)

-- 1) New table: tournament_stage
CREATE TABLE IF NOT EXISTS tournament_stage (
  id INT NOT NULL AUTO_INCREMENT,
  tournament_id INT NOT NULL,
  stage_index INT NOT NULL,
  name VARCHAR(255) NULL,
  type VARCHAR(32) NOT NULL, -- 'groups' | 'knockout'
  number_of_groups INT NULL,
  advancing_per_group INT NULL,
  max_group_size INT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  CONSTRAINT fk_tournament_stage_tournament
    FOREIGN KEY (tournament_id) REFERENCES tournament(id)
    ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE INDEX idx_tournament_stage_tournament_id ON tournament_stage (tournament_id);
CREATE UNIQUE INDEX uq_tournament_stage_tournament_id_index ON tournament_stage (tournament_id, stage_index);

-- 2) New table: tournament_stage_advancement
CREATE TABLE IF NOT EXISTS tournament_stage_advancement (
  id INT NOT NULL AUTO_INCREMENT,
  tournament_id INT NOT NULL,
  from_stage_id INT NOT NULL,
  to_stage_id INT NOT NULL,
  mode VARCHAR(32) NOT NULL DEFAULT 'pools',
  config JSON NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  CONSTRAINT fk_tournament_stage_adv_tournament
    FOREIGN KEY (tournament_id) REFERENCES tournament(id)
    ON DELETE CASCADE,
  CONSTRAINT fk_tournament_stage_adv_from
    FOREIGN KEY (from_stage_id) REFERENCES tournament_stage(id)
    ON DELETE CASCADE,
  CONSTRAINT fk_tournament_stage_adv_to
    FOREIGN KEY (to_stage_id) REFERENCES tournament_stage(id)
    ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE INDEX idx_tournament_stage_adv_tournament_id ON tournament_stage_advancement (tournament_id);
CREATE INDEX idx_tournament_stage_adv_from_stage_id ON tournament_stage_advancement (from_stage_id);
CREATE INDEX idx_tournament_stage_adv_to_stage_id ON tournament_stage_advancement (to_stage_id);

-- 3) Add stage_id to tournament_group and tournament_match
-- MariaDB has no IF NOT EXISTS for columns; run each ALTER once.
-- If you rerun, comment out the ALTERs or check INFORMATION_SCHEMA first.
ALTER TABLE tournament_group ADD COLUMN stage_id INT NULL;
ALTER TABLE tournament_match ADD COLUMN stage_id INT NULL;

CREATE INDEX idx_tournament_group_tournament_stage ON tournament_group (tournament_id, stage_id);
CREATE INDEX idx_tournament_match_tournament_stage ON tournament_match (tournament_id, stage_id);
