-- Única completion por persona/tarea/periodo (evita duplicados involuntarios)
SET @ix := (SELECT 1 FROM information_schema.statistics
            WHERE table_schema = DATABASE() AND table_name='task_completions' AND index_name='uk_task_person_period' LIMIT 1);
SET @sql := IF(@ix IS NULL,
  'ALTER TABLE task_completions ADD UNIQUE KEY uk_task_person_period (task_id, person_id, period_id)',
  'SELECT 1');
PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;

-- Ganador de tareas generales (asegura SOLO un ganador por task+periodo)
CREATE TABLE IF NOT EXISTS task_general_wins (
  task_id INT NOT NULL,
  period_id INT NOT NULL,
  person_id INT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (task_id, period_id),
  FOREIGN KEY (task_id)  REFERENCES tasks(id)   ON DELETE CASCADE,
  FOREIGN KEY (period_id) REFERENCES periods(id) ON DELETE CASCADE,
  FOREIGN KEY (person_id) REFERENCES people(id)  ON DELETE CASCADE
);
