-- Create cohorts table and add cohort_id to course_enrollments

CREATE TABLE `cohorts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `course_id` int(11) NOT NULL,
  `instructor_id` int(11) NOT NULL,
  `region` enum('usa','europe','africa','global') NOT NULL DEFAULT 'global',
  `title` varchar(255) DEFAULT NULL,
  `max_capacity` int(11) DEFAULT NULL,
  `start_date` datetime DEFAULT NULL,
  `end_date` datetime DEFAULT NULL,
  `status` enum('open','closed','ongoing','completed') NOT NULL DEFAULT 'open',
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_course_id` (`course_id`),
  KEY `idx_instructor_id` (`instructor_id`),
  KEY `idx_region` (`region`),
  KEY `idx_status` (`status`),
  CONSTRAINT `fk_cohorts_course_id` FOREIGN KEY (`course_id`) REFERENCES `courses` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_cohorts_instructor_id` FOREIGN KEY (`instructor_id`) REFERENCES `users` (`id`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

ALTER TABLE `course_enrollments`
  ADD COLUMN `cohort_id` int(11) DEFAULT NULL AFTER `student_id`,
  ADD KEY `idx_cohort_id` (`cohort_id`),
  ADD CONSTRAINT `fk_course_enrollments_cohort_id` FOREIGN KEY (`cohort_id`) REFERENCES `cohorts` (`id`) ON DELETE SET NULL;
