-- Migration: Add season_id to teams table
-- First, add the column as nullable
ALTER TABLE `team` ADD COLUMN `season_id` INT NULL;

-- Get or create current season
SET @current_season_id = (
    SELECT id FROM `season` 
    WHERE season = (
        CASE 
            WHEN MONTH(CURDATE()) >= 7 THEN CONCAT(YEAR(CURDATE()), '/', YEAR(CURDATE()) + 1)
            ELSE CONCAT(YEAR(CURDATE()) - 1, '/', YEAR(CURDATE()))
        END
    )
    LIMIT 1
);

-- If no season exists, create it
INSERT IGNORE INTO `season` (season) VALUES (
    CASE 
        WHEN MONTH(CURDATE()) >= 7 THEN CONCAT(YEAR(CURDATE()), '/', YEAR(CURDATE()) + 1)
        ELSE CONCAT(YEAR(CURDATE()) - 1, '/', YEAR(CURDATE()))
    END
);

-- Get the season ID again (in case we just created it)
SET @current_season_id = (
    SELECT id FROM `season` 
    WHERE season = (
        CASE 
            WHEN MONTH(CURDATE()) >= 7 THEN CONCAT(YEAR(CURDATE()), '/', YEAR(CURDATE()) + 1)
            ELSE CONCAT(YEAR(CURDATE()) - 1, '/', YEAR(CURDATE()))
        END
    )
    LIMIT 1
);

-- Update all existing teams to use the current season
UPDATE `team` SET `season_id` = @current_season_id WHERE `season_id` IS NULL;

-- Now make the column NOT NULL and add the foreign key constraint
ALTER TABLE `team` MODIFY COLUMN `season_id` INT NOT NULL;
ALTER TABLE `team` ADD CONSTRAINT `team_season_id_foreign_idx` 
    FOREIGN KEY (`season_id`) REFERENCES `season` (`id`) 
    ON DELETE CASCADE ON UPDATE CASCADE;
