-- CoreEdu 服务数据库初始化脚本
-- 表：core_edu_exams / core_edu_homework / core_edu_grades / core_edu_outbox

CREATE TABLE IF NOT EXISTS core_edu_exams (
  id CHAR(36) NOT NULL PRIMARY KEY,
  class_id CHAR(36) NOT NULL,
  title VARCHAR(200) NOT NULL,
  description TEXT,
  exam_date DATETIME NOT NULL,
  duration VARCHAR(50) NOT NULL,
  total_score VARCHAR(10) NOT NULL,
  status VARCHAR(20) NOT NULL DEFAULT 'draft',
  created_by CHAR(36) NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX idx_exams_class_id (class_id),
  INDEX idx_exams_status (status),
  INDEX idx_exams_created_by (created_by)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS core_edu_homework (
  id CHAR(36) NOT NULL PRIMARY KEY,
  class_id CHAR(36) NOT NULL,
  title VARCHAR(200) NOT NULL,
  description TEXT,
  due_date DATETIME NOT NULL,
  status VARCHAR(20) NOT NULL DEFAULT 'assigned',
  created_by CHAR(36) NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX idx_homework_class_id (class_id),
  INDEX idx_homework_status (status),
  INDEX idx_homework_created_by (created_by)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS core_edu_grades (
  id CHAR(36) NOT NULL PRIMARY KEY,
  student_id CHAR(36) NOT NULL,
  exam_id CHAR(36),
  homework_id CHAR(36),
  score VARCHAR(10) NOT NULL,
  feedback TEXT,
  graded_by CHAR(36) NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX idx_grades_student_id (student_id),
  INDEX idx_grades_exam_id (exam_id),
  INDEX idx_grades_homework_id (homework_id),
  INDEX idx_grades_graded_by (graded_by)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS core_edu_outbox (
  id CHAR(36) NOT NULL PRIMARY KEY,
  aggregate_id CHAR(36) NOT NULL,
  aggregate_type VARCHAR(50) NOT NULL,
  event_type VARCHAR(100) NOT NULL,
  payload TEXT NOT NULL,
  status VARCHAR(20) NOT NULL DEFAULT 'pending',
  retry_count BIGINT NOT NULL DEFAULT 0,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  processed_at TIMESTAMP NULL,
  INDEX idx_outbox_status (status),
  INDEX idx_outbox_aggregate (aggregate_type, aggregate_id),
  INDEX idx_outbox_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
