-- ============================================================
-- PTA V5.13 - Contrôle de couverture des lieux d'affectation
-- MySQL 8+
-- ============================================================

CREATE TABLE IF NOT EXISTS structure_couverture_horaire (
    id_couverture INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    id_structure INT UNSIGNED NOT NULL,
    jour_semaine TINYINT UNSIGNED NOT NULL COMMENT '1=lundi, 5=vendredi',
    heure_debut TIME NOT NULL,
    heure_fin TIME NOT NULL,
    minimum_agents TINYINT UNSIGNED NOT NULL DEFAULT 1,

    CONSTRAINT fk_couverture_structure
        FOREIGN KEY (id_structure)
        REFERENCES structure(id_structure)
        ON UPDATE CASCADE
        ON DELETE CASCADE,

    CONSTRAINT chk_couverture_jour
        CHECK (jour_semaine BETWEEN 1 AND 5),

    CONSTRAINT chk_couverture_ordre
        CHECK (heure_fin > heure_debut),

    CONSTRAINT chk_couverture_minimum
        CHECK (minimum_agents BETWEEN 1 AND 50),

    CONSTRAINT chk_couverture_quart_heure
        CHECK (
            MOD(MINUTE(heure_debut), 15) = 0
            AND MOD(MINUTE(heure_fin), 15) = 0
            AND SECOND(heure_debut) = 0
            AND SECOND(heure_fin) = 0
        )
) ENGINE = InnoDB;

CREATE INDEX idx_couverture_structure_jour
    ON structure_couverture_horaire(id_structure, jour_semaine, heure_debut, heure_fin);
