-- ============================================================
-- PTA V4.5 - Une structure principale par agent
-- MySQL 8+
-- ============================================================

SET @col_exists = (
    SELECT COUNT(*)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'agent'
      AND COLUMN_NAME = 'id_structure'
);

SET @sql = IF(
    @col_exists = 0,
    'ALTER TABLE agent ADD COLUMN id_structure INT UNSIGNED NULL AFTER email',
    'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @fk_exists = (
    SELECT COUNT(*)
    FROM information_schema.REFERENTIAL_CONSTRAINTS
    WHERE CONSTRAINT_SCHEMA = DATABASE()
      AND TABLE_NAME = 'agent'
      AND CONSTRAINT_NAME = 'fk_agent_structure_principale'
);

SET @sql = IF(
    @fk_exists = 0,
    'ALTER TABLE agent ADD CONSTRAINT fk_agent_structure_principale FOREIGN KEY (id_structure) REFERENCES structure(id_structure) ON UPDATE CASCADE ON DELETE SET NULL',
    'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @idx_exists = (
    SELECT COUNT(*)
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'agent'
      AND INDEX_NAME = 'idx_agent_structure_principale'
);
SET @sql = IF(
    @idx_exists = 0,
    'CREATE INDEX idx_agent_structure_principale ON agent(id_structure)',
    'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Reprise automatique uniquement lorsqu'un agent n'a qu'un seul rattachement actif.
UPDATE agent a
JOIN (
    SELECT id_agent, MIN(id_structure) AS id_structure
    FROM agent_structure
    WHERE actif = TRUE
      AND (date_fin IS NULL OR date_fin >= CURRENT_DATE)
    GROUP BY id_agent
    HAVING COUNT(DISTINCT id_structure) = 1
) x ON x.id_agent = a.id_agent
SET a.id_structure = x.id_structure
WHERE a.id_structure IS NULL;

-- Les agents encore sans structure doivent être affectés depuis l'onglet
-- "Gestion des agents" de l'application.
