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

// 成绩主表
export const grades = mysqlTable(
  "core_edu_grades",
  {
    id: char("id", { length: 36 }).notNull().primaryKey(),
    studentId: char("student_id", { length: 36 }).notNull(),
    examId: char("exam_id", { length: 36 }),
    homeworkId: char("homework_id", { length: 36 }),
    score: decimal("score", { precision: 6, scale: 2 }).notNull(),
    totalScore: decimal("total_score", { precision: 6, scale: 2 }).notNull(),
    feedback: text("feedback"),
    gradedBy: char("graded_by", { length: 36 }).notNull(),
    schoolId: char("school_id", { length: 36 }).notNull(),
    idempotencyKey: varchar("idempotency_key", { length: 128 }),
    createdAt: timestamp("created_at").notNull().defaultNow(),
    updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
  },
  (table) => ({
    uniqStudentExam: uniqueIndex("uniq_student_exam").on(
      table.studentId,
      table.examId,
    ),
    uniqStudentHw: uniqueIndex("uniq_student_hw").on(
      table.studentId,
      table.homeworkId,
    ),
    uniqIdempotency: uniqueIndex("uniq_idempotency").on(table.idempotencyKey),
    idxGradesStudentId: index("idx_grades_student_id").on(table.studentId),
    idxGradesExamId: index("idx_grades_exam_id").on(table.examId),
    idxGradesHomeworkId: index("idx_grades_homework_id").on(table.homeworkId),
    idxGradesGradedBy: index("idx_grades_graded_by").on(table.gradedBy),
  }),
);

// 成绩公式表（按 scope 优先级：class > subject > school）
export const gradeFormulas = mysqlTable(
  "core_edu_grade_formulas",
  {
    id: char("id", { length: 36 }).notNull().primaryKey(),
    scope: varchar("scope", { length: 20 }).notNull(), // class | subject | school
    scopeId: char("scope_id", { length: 36 }).notNull(),
    formulaType: varchar("formula_type", { length: 20 }).notNull(),
    weights: json("weights"),
    customExpression: text("custom_expression"),
    effectiveFrom: datetime("effective_from").notNull(),
    effectiveTo: datetime("effective_to"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (table) => ({
    idxGradeFormulasScope: index("idx_grade_formulas_scope").on(
      table.scope,
      table.scopeId,
    ),
    idxGradeFormulasEffective: index("idx_grade_formulas_effective").on(
      table.effectiveFrom,
      table.effectiveTo,
    ),
  }),
);

export type Grade = typeof grades.$inferSelect;
export type NewGrade = typeof grades.$inferInsert;
export type GradeFormula = typeof gradeFormulas.$inferSelect;
export type NewGradeFormula = typeof gradeFormulas.$inferInsert;
