import { relations } from "drizzle-orm";
import {
  users,
  accounts,
  sessions,
  roles,
  usersToRoles,
  questions,
  knowledgePoints,
  questionsToKnowledgePoints,
  textbooks,
  chapters,
  schools,
  grades,
  classes,
  classEnrollments,
  classSchedule,
  subjects,
  exams,
  examQuestions,
  examSubmissions,
  submissionAnswers,
  homeworkAssignments,
  homeworkAssignmentQuestions,
  homeworkAssignmentTargets,
  homeworkSubmissions,
  homeworkAnswers,
  announcements,
  coursePlans,
  coursePlanItems,
  gradeRecords,
  messages,
  messageNotifications,
  parentStudentRelations,
  attendanceRecords,
  attendanceRules,
  passwordSecurity,
  errorBookItems,
  errorBookReviews,
} from "./schema";

// --- Users & Roles Relations ---

export const usersRelations = relations(users, ({ many, one }) => ({
  accounts: many(accounts),
  sessions: many(sessions),
  usersToRoles: many(usersToRoles),
  teachingClasses: many(classes),
  classEnrollments: many(classEnrollments),
  createdExams: many(exams),
  createdHomeworkAssignments: many(homeworkAssignments),
  submissions: many(examSubmissions),
  homeworkSubmissions: many(homeworkSubmissions),
  authoredQuestions: many(questions),
  authoredAnnouncements: many(announcements),
  sentMessages: many(messages, { relationName: "message_sender" }),
  receivedMessages: many(messages, { relationName: "message_receiver" }),
  notifications: many(messageNotifications),
  passwordSecurity: one(passwordSecurity),
  errorBookItems: many(errorBookItems),
  errorBookReviews: many(errorBookReviews),
}));

export const accountsRelations = relations(accounts, ({ one }) => ({
  user: one(users, {
    fields: [accounts.userId],
    references: [users.id],
  }),
}));

export const sessionsRelations = relations(sessions, ({ one }) => ({
  user: one(users, {
    fields: [sessions.userId],
    references: [users.id],
  }),
}));

export const rolesRelations = relations(roles, ({ many }) => ({
  usersToRoles: many(usersToRoles),
}));

export const usersToRolesRelations = relations(usersToRoles, ({ one }) => ({
  user: one(users, {
    fields: [usersToRoles.userId],
    references: [users.id],
  }),
  role: one(roles, {
    fields: [usersToRoles.roleId],
    references: [roles.id],
  }),
}));

// --- Questions Relations (Self-Reference & KP) ---

export const questionsRelations = relations(questions, ({ one, many }) => ({
  author: one(users, {
    fields: [questions.authorId],
    references: [users.id],
  }),
  // Self-Reference: Parent Question
  parent: one(questions, {
    fields: [questions.parentId],
    references: [questions.id],
    relationName: "question_hierarchy",
  }),
  // Self-Reference: Child Questions
  children: many(questions, {
    relationName: "question_hierarchy",
  }),

  // Many-to-Many with Knowledge Points (Direct relation mapping)
  knowledgePoints: many(questionsToKnowledgePoints),

  // Usage in Exams
  examQuestions: many(examQuestions),

  // Error book items referencing this question
  errorBookItems: many(errorBookItems),
}));

export const knowledgePointsRelations = relations(knowledgePoints, ({ one, many }) => ({
  // Tree Structure
  parent: one(knowledgePoints, {
    fields: [knowledgePoints.parentId],
    references: [knowledgePoints.id],
    relationName: "kp_hierarchy",
  }),
  children: many(knowledgePoints, {
    relationName: "kp_hierarchy",
  }),

  chapter: one(chapters, {
    fields: [knowledgePoints.chapterId],
    references: [chapters.id],
  }),
  
  questionsToKnowledgePoints: many(questionsToKnowledgePoints),
}));

export const questionsToKnowledgePointsRelations = relations(questionsToKnowledgePoints, ({ one }) => ({
  question: one(questions, {
    fields: [questionsToKnowledgePoints.questionId],
    references: [questions.id],
  }),
  knowledgePoint: one(knowledgePoints, {
    fields: [questionsToKnowledgePoints.knowledgePointId],
    references: [knowledgePoints.id],
  }),
}));

// --- Academic Relations ---

export const textbooksRelations = relations(textbooks, ({ many }) => ({
  chapters: many(chapters),
}));

export const chaptersRelations = relations(chapters, ({ one, many }) => ({
  textbook: one(textbooks, {
    fields: [chapters.textbookId],
    references: [textbooks.id],
  }),
  parent: one(chapters, {
    fields: [chapters.parentId],
    references: [chapters.id],
    relationName: "chapter_hierarchy",
  }),
  children: many(chapters, {
    relationName: "chapter_hierarchy",
  }),

  knowledgePoints: many(knowledgePoints),
}));

export const schoolsRelations = relations(schools, ({ many }) => ({
  grades: many(grades),
  classes: many(classes),
}))

export const gradesRelations = relations(grades, ({ one, many }) => ({
  school: one(schools, {
    fields: [grades.schoolId],
    references: [schools.id],
  }),
  gradeHead: one(users, {
    fields: [grades.gradeHeadId],
    references: [users.id],
  }),
  teachingHead: one(users, {
    fields: [grades.teachingHeadId],
    references: [users.id],
  }),
  classes: many(classes),
}))

export const classesRelations = relations(classes, ({ one, many }) => ({
  teacher: one(users, {
    fields: [classes.teacherId],
    references: [users.id],
  }),
  school: one(schools, {
    fields: [classes.schoolId],
    references: [schools.id],
  }),
  gradeEntity: one(grades, {
    fields: [classes.gradeId],
    references: [grades.id],
  }),
  enrollments: many(classEnrollments),
  scheduleItems: many(classSchedule),
}));

export const classEnrollmentsRelations = relations(classEnrollments, ({ one }) => ({
  class: one(classes, {
    fields: [classEnrollments.classId],
    references: [classes.id],
  }),
  student: one(users, {
    fields: [classEnrollments.studentId],
    references: [users.id],
  }),
}));

export const classScheduleRelations = relations(classSchedule, ({ one }) => ({
  class: one(classes, {
    fields: [classSchedule.classId],
    references: [classes.id],
  }),
}));

export const examsRelations = relations(exams, ({ one, many }) => ({
  creator: one(users, {
    fields: [exams.creatorId],
    references: [users.id],
  }),
  subject: one(subjects, {
    fields: [exams.subjectId],
    references: [subjects.id],
  }),
  gradeEntity: one(grades, {
    fields: [exams.gradeId],
    references: [grades.id],
  }),
  questions: many(examQuestions),
  submissions: many(examSubmissions),
}));

export const examQuestionsRelations = relations(examQuestions, ({ one }) => ({
  exam: one(exams, {
    fields: [examQuestions.examId],
    references: [exams.id],
  }),
  question: one(questions, {
    fields: [examQuestions.questionId],
    references: [questions.id],
  }),
}));

export const examSubmissionsRelations = relations(examSubmissions, ({ one, many }) => ({
  exam: one(exams, {
    fields: [examSubmissions.examId],
    references: [exams.id],
  }),
  student: one(users, {
    fields: [examSubmissions.studentId],
    references: [users.id],
  }),
  answers: many(submissionAnswers),
}));

export const submissionAnswersRelations = relations(submissionAnswers, ({ one }) => ({
  submission: one(examSubmissions, {
    fields: [submissionAnswers.submissionId],
    references: [examSubmissions.id],
  }),
  question: one(questions, {
    fields: [submissionAnswers.questionId],
    references: [questions.id],
  }),
}));

export const homeworkAssignmentsRelations = relations(homeworkAssignments, ({ one, many }) => ({
  creator: one(users, {
    fields: [homeworkAssignments.creatorId],
    references: [users.id],
  }),
  sourceExam: one(exams, {
    fields: [homeworkAssignments.sourceExamId],
    references: [exams.id],
  }),
  questions: many(homeworkAssignmentQuestions),
  targets: many(homeworkAssignmentTargets),
  submissions: many(homeworkSubmissions),
}));

export const homeworkAssignmentQuestionsRelations = relations(homeworkAssignmentQuestions, ({ one }) => ({
  assignment: one(homeworkAssignments, {
    fields: [homeworkAssignmentQuestions.assignmentId],
    references: [homeworkAssignments.id],
  }),
  question: one(questions, {
    fields: [homeworkAssignmentQuestions.questionId],
    references: [questions.id],
  }),
}));

export const homeworkAssignmentTargetsRelations = relations(homeworkAssignmentTargets, ({ one }) => ({
  assignment: one(homeworkAssignments, {
    fields: [homeworkAssignmentTargets.assignmentId],
    references: [homeworkAssignments.id],
  }),
  student: one(users, {
    fields: [homeworkAssignmentTargets.studentId],
    references: [users.id],
  }),
}));

export const homeworkSubmissionsRelations = relations(homeworkSubmissions, ({ one, many }) => ({
  assignment: one(homeworkAssignments, {
    fields: [homeworkSubmissions.assignmentId],
    references: [homeworkAssignments.id],
  }),
  student: one(users, {
    fields: [homeworkSubmissions.studentId],
    references: [users.id],
  }),
  answers: many(homeworkAnswers),
}));

export const homeworkAnswersRelations = relations(homeworkAnswers, ({ one }) => ({
  submission: one(homeworkSubmissions, {
    fields: [homeworkAnswers.submissionId],
    references: [homeworkSubmissions.id],
  }),
  question: one(questions, {
    fields: [homeworkAnswers.questionId],
    references: [questions.id],
  }),
}));

// --- Announcements Relations ---

export const announcementsRelations = relations(announcements, ({ one }) => ({
  author: one(users, {
    fields: [announcements.authorId],
    references: [users.id],
  }),
  targetGrade: one(grades, {
    fields: [announcements.targetGradeId],
    references: [grades.id],
  }),
  targetClass: one(classes, {
    fields: [announcements.targetClassId],
    references: [classes.id],
  }),
}));

// --- Course Plans Relations ---

export const coursePlansRelations = relations(coursePlans, ({ one, many }) => ({
  class: one(classes, {
    fields: [coursePlans.classId],
    references: [classes.id],
  }),
  subject: one(subjects, {
    fields: [coursePlans.subjectId],
    references: [subjects.id],
  }),
  teacher: one(users, {
    fields: [coursePlans.teacherId],
    references: [users.id],
    relationName: "course_plan_teacher",
  }),
  createdByUser: one(users, {
    fields: [coursePlans.createdBy],
    references: [users.id],
    relationName: "course_plan_creator",
  }),
  items: many(coursePlanItems),
}));

export const coursePlanItemsRelations = relations(coursePlanItems, ({ one }) => ({
  plan: one(coursePlans, {
    fields: [coursePlanItems.planId],
    references: [coursePlans.id],
  }),
}));

// --- Grade Records Relations ---

export const gradeRecordsRelations = relations(gradeRecords, ({ one }) => ({
  student: one(users, {
    fields: [gradeRecords.studentId],
    references: [users.id],
    relationName: "grade_records_student",
  }),
  class: one(classes, {
    fields: [gradeRecords.classId],
    references: [classes.id],
  }),
  subject: one(subjects, {
    fields: [gradeRecords.subjectId],
    references: [subjects.id],
  }),
  exam: one(exams, {
    fields: [gradeRecords.examId],
    references: [exams.id],
  }),
  recorder: one(users, {
    fields: [gradeRecords.recordedBy],
    references: [users.id],
    relationName: "grade_records_recorder",
  }),
}));

// --- Messages Relations ---

export const messagesRelations = relations(messages, ({ one, many }) => ({
  sender: one(users, {
    fields: [messages.senderId],
    references: [users.id],
    relationName: "message_sender",
  }),
  receiver: one(users, {
    fields: [messages.receiverId],
    references: [users.id],
    relationName: "message_receiver",
  }),
  parent: one(messages, {
    fields: [messages.parentMessageId],
    references: [messages.id],
    relationName: "message_thread",
  }),
  replies: many(messages, { relationName: "message_thread" }),
}));

// --- Message Notifications Relations ---

export const messageNotificationsRelations = relations(messageNotifications, ({ one }) => ({
  user: one(users, {
    fields: [messageNotifications.userId],
    references: [users.id],
  }),
}));

// --- Parent-Student Relations ---

export const parentStudentRelationsRelations = relations(parentStudentRelations, ({ one }) => ({
  parent: one(users, {
    fields: [parentStudentRelations.parentId],
    references: [users.id],
    relationName: "parent_relations",
  }),
  student: one(users, {
    fields: [parentStudentRelations.studentId],
    references: [users.id],
    relationName: "student_relations",
  }),
}));

// --- Attendance Relations ---

export const attendanceRecordsRelations = relations(attendanceRecords, ({ one }) => ({
  student: one(users, {
    fields: [attendanceRecords.studentId],
    references: [users.id],
    relationName: "attendance_records_student",
  }),
  class: one(classes, {
    fields: [attendanceRecords.classId],
    references: [classes.id],
  }),
  recorder: one(users, {
    fields: [attendanceRecords.recordedBy],
    references: [users.id],
    relationName: "attendance_records_recorder",
  }),
}));

export const attendanceRulesRelations = relations(attendanceRules, ({ one }) => ({
  class: one(classes, {
    fields: [attendanceRules.classId],
    references: [classes.id],
  }),
}));

// --- Password Security Relations ---

export const passwordSecurityRelations = relations(passwordSecurity, ({ one }) => ({
  user: one(users, {
    fields: [passwordSecurity.userId],
    references: [users.id],
  }),
}));

// --- Error Book Relations ---

export const errorBookItemsRelations = relations(errorBookItems, ({ one, many }) => ({
  student: one(users, {
    fields: [errorBookItems.studentId],
    references: [users.id],
  }),
  question: one(questions, {
    fields: [errorBookItems.questionId],
    references: [questions.id],
  }),
  subject: one(subjects, {
    fields: [errorBookItems.subjectId],
    references: [subjects.id],
  }),
  reviews: many(errorBookReviews),
}));

export const errorBookReviewsRelations = relations(errorBookReviews, ({ one }) => ({
  item: one(errorBookItems, {
    fields: [errorBookReviews.itemId],
    references: [errorBookItems.id],
  }),
  student: one(users, {
    fields: [errorBookReviews.studentId],
    references: [users.id],
  }),
}));
