-- =====================================================
-- Teams
-- =====================================================

DROP TABLE IF EXISTS `team_members`;
DROP TABLE IF EXISTS `teams`;


-- -----------------------------------------------------
-- Teams table
-- -----------------------------------------------------
CREATE TABLE `teams` (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    name            VARCHAR(100) NOT NULL,
    abbreviation    VARCHAR(10) NOT NULL,
    join_password   VARCHAR(255) NOT NULL,
    created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,

    UNIQUE KEY uq_team_name (name),
    UNIQUE KEY uq_team_abbr (abbreviation)

) ENGINE=InnoDB
  DEFAULT CHARSET=utf8mb4
  COLLATE=utf8mb4_unicode_ci;


-- -----------------------------------------------------
-- Team Members (Junction Table)
-- -----------------------------------------------------
CREATE TABLE `team_members` (
    team_id     INT NOT NULL,
    user_id     INT NOT NULL,

    status      ENUM('MEMBER','OFFICER','LEADER')
                    NOT NULL DEFAULT 'MEMBER',

    joined_at   DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,

    PRIMARY KEY (team_id, user_id),

    CONSTRAINT fk_tm_team
        FOREIGN KEY (team_id)
        REFERENCES teams(id)
        ON DELETE CASCADE,

    CONSTRAINT fk_tm_user
        FOREIGN KEY (user_id)
        REFERENCES users(user_id)
        ON DELETE CASCADE

) ENGINE=InnoDB
  DEFAULT CHARSET=utf8mb4
  COLLATE=utf8mb4_unicode_ci;


-- -----------------------------------------------------
-- Indexes
-- -----------------------------------------------------
CREATE INDEX idx_tm_user
    ON team_members(user_id);

CREATE INDEX idx_tm_team_status
    ON team_members(team_id, status);
