import {
  mysqlTable,
  varchar,
  timestamp,
  char,
  datetime,
  date,
  int,
  json,
  index,
} from "drizzle-orm/mysql-core";

// 课程表
export const courses = mysqlTable(
  "core_edu_courses",
  {
    id: char("id", { length: 36 }).notNull().primaryKey(),
    classId: char("class_id", { length: 36 }).notNull(),
    subjectId: char("subject_id", { length: 36 }).notNull(),
    teacherId: char("teacher_id", { length: 36 }).notNull(),
    schoolId: char("school_id", { length: 36 }).notNull(),
    name: varchar("name", { length: 200 }).notNull(),
    startDate: date("start_date").notNull(),
    endDate: date("end_date").notNull(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
    updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
  },
  (table) => ({
    idxCoursesClassId: index("idx_courses_class_id").on(table.classId),
    idxCoursesTeacherId: index("idx_courses_teacher_id").on(table.teacherId),
  }),
);

// 课次表
export const lessons = mysqlTable(
  "core_edu_lessons",
  {
    id: char("id", { length: 36 }).notNull().primaryKey(),
    courseId: char("course_id", { length: 36 }).notNull(),
    title: varchar("title", { length: 200 }).notNull(),
    order: int("order").notNull(),
    knowledgePointIds: json("knowledge_point_ids"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (table) => ({
    idxLessonsCourseId: index("idx_lessons_course_id").on(table.courseId),
  }),
);

// 排课表
export const schedules = mysqlTable(
  "core_edu_schedules",
  {
    id: char("id", { length: 36 }).notNull().primaryKey(),
    courseId: char("course_id", { length: 36 }).notNull(),
    lessonId: char("lesson_id", { length: 36 }),
    teacherId: char("teacher_id", { length: 36 }).notNull(),
    classId: char("class_id", { length: 36 }).notNull(),
    roomId: char("room_id", { length: 36 }), // P3 仅预留，不校验冲突
    startTime: datetime("start_time").notNull(),
    endTime: datetime("end_time").notNull(),
    status: varchar("status", { length: 20 }).notNull().default("scheduled"),
    schoolId: char("school_id", { length: 36 }).notNull(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
    updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
  },
  (table) => ({
    idxSchedulesTeacherTime: index("idx_schedules_teacher_time").on(
      table.teacherId,
      table.startTime,
      table.endTime,
    ),
    idxSchedulesClassTime: index("idx_schedules_class_time").on(
      table.classId,
      table.startTime,
      table.endTime,
    ),
    idxSchedulesCourseId: index("idx_schedules_course_id").on(table.courseId),
  }),
);

export type Course = typeof courses.$inferSelect;
export type NewCourse = typeof courses.$inferInsert;
export type Lesson = typeof lessons.$inferSelect;
export type NewLesson = typeof lessons.$inferInsert;
export type Schedule = typeof schedules.$inferSelect;
export type NewSchedule = typeof schedules.$inferInsert;
