-- ========================================
-- Script OPTIMISÉ d'ajout de contraintes UNIQUE
-- Pour tables avec beaucoup de données
-- Date: 2025-10-10
-- ========================================

USE pra_geo;

-- ========================================
-- OPTION 1 : Compter les doublons d'abord
-- ========================================

SELECT 'Analyse des doublons dans ope_users...' as status;
SELECT COUNT(*) as total_rows,
       COUNT(DISTINCT fk_operation, fk_user) as unique_combinations,
       COUNT(*) - COUNT(DISTINCT fk_operation, fk_user) as duplicates
FROM ope_users;

SELECT 'Analyse des doublons dans ope_users_sectors...' as status;
SELECT COUNT(*) as total_rows,
       COUNT(DISTINCT fk_operation, fk_user, fk_sector) as unique_combinations,
       COUNT(*) - COUNT(DISTINCT fk_operation, fk_user, fk_sector) as duplicates
FROM ope_users_sectors;

-- ========================================
-- OPTION 2 : Supprimer RAPIDEMENT les doublons
-- Créer une table temporaire avec les IDs à garder
-- ========================================

-- Pour ope_users
CREATE TEMPORARY TABLE ope_users_to_keep AS
SELECT MIN(id) as id_to_keep, fk_operation, fk_user
FROM ope_users
GROUP BY fk_operation, fk_user;

-- Supprimer tous les doublons (plus rapide avec NOT IN + subquery)
DELETE FROM ope_users
WHERE id NOT IN (SELECT id_to_keep FROM ope_users_to_keep);

DROP TEMPORARY TABLE ope_users_to_keep;

-- Pour ope_users_sectors
CREATE TEMPORARY TABLE ope_users_sectors_to_keep AS
SELECT MIN(id) as id_to_keep, fk_operation, fk_user, fk_sector
FROM ope_users_sectors
GROUP BY fk_operation, fk_user, fk_sector;

DELETE FROM ope_users_sectors
WHERE id NOT IN (SELECT id_to_keep FROM ope_users_sectors_to_keep);

DROP TEMPORARY TABLE ope_users_sectors_to_keep;

-- ========================================
-- OPTION 3 : Ajouter les contraintes UNIQUE
-- ========================================

ALTER TABLE ope_users
ADD UNIQUE KEY `idx_operation_user` (`fk_operation`, `fk_user`);

ALTER TABLE ope_users_sectors
ADD UNIQUE KEY `idx_operation_user_sector` (`fk_operation`, `fk_user`, `fk_sector`);

-- ========================================
-- Vérification finale
-- ========================================

SHOW INDEX FROM ope_users WHERE Key_name = 'idx_operation_user';
SHOW INDEX FROM ope_users_sectors WHERE Key_name = 'idx_operation_user_sector';

SELECT 'TERMINÉ - Contraintes UNIQUE ajoutées avec succès' as status;
