// GraphQL operations 文档
// 依据：02-architecture-design.md §4.2 GraphQL 接入、F9 裁决（首次即 GraphQL）
// 端点：POST /api/v1/parent/v1/graphql（双 /v1 前缀，ARB-022 §24.4 ISSUE-003 方案 A）
// 命名：查询 PascalCase（CurrentUser / MyChildren / ChildSummary ...）
//
// 所有查询/变更与 parent-bff 契约对齐：
// - 查询：currentUser / myChildren / childSummary / childGrades / childAttendance /
//        childHomework / childWeakness / childTrend / childExams / childExamResult /
//        childClasses / childLearningPath / myNotifications / myNotificationPreferences
// - 变更：markAsRead / markAllAsRead / updateNotificationPreferences

import { gql } from "urql";

// ===== 查询 =====

export const CURRENT_USER = gql`
  query CurrentUser {
    currentUser {
      id
      email
      name
      roles
      permissions
      dataScope
      schoolId
    }
  }
`;

export const MY_CHILDREN = gql`
  query MyChildren {
    myChildren {
      id
      name
      avatar
      grade
      schoolName
      classId
      className
      isArchived
    }
  }
`;

export const CHILD_SUMMARY = gql`
  query ChildSummary($childId: ID!) {
    childSummary(childId: $childId) {
      childId
      avgScore
      classRank
      classSize
      attendanceRate
      pendingHomeworkCount
      recentGradeTrend
      recentScores {
        examId
        examName
        examDate
        subject
        studentScore
        classAverage
        classMax
        classMin
        gradeLevel
      }
      upcomingEvents {
        id
        type
        title
        dueDate
      }
    }
  }
`;

export const CHILD_GRADES = gql`
  query ChildGrades($childId: ID!, $subject: String, $limit: Int) {
    childGrades(childId: $childId, subject: $subject, limit: $limit) {
      examId
      examName
      examDate
      subject
      studentScore
      classAverage
      classMax
      classMin
      gradeLevel
    }
  }
`;

export const CHILD_ATTENDANCE = gql`
  query ChildAttendance($childId: ID!, $startDate: String!, $endDate: String!) {
    childAttendance(
      childId: $childId
      startDate: $startDate
      endDate: $endDate
    ) {
      id
      date
      status
      note
    }
  }
`;

export const CHILD_HOMEWORK = gql`
  query ChildHomework($childId: ID!, $status: String) {
    childHomework(childId: $childId, status: $status) {
      id
      title
      subject
      className
      assignedDate
      dueDate
      status
      score
      maxScore
      feedback
    }
  }
`;

export const CHILD_WEAKNESS = gql`
  query ChildWeakness($childId: ID!) {
    childWeakness(childId: $childId) {
      id
      knowledgePoint
      masteryLevel
      subject
      recommendation
    }
  }
`;

export const CHILD_TREND = gql`
  query ChildTrend($childId: ID!, $period: TrendPeriod!) {
    childTrend(childId: $childId, period: $period) {
      childId
      period
      dataPoints {
        date
        score
        subject
      }
    }
  }
`;

export const CHILD_EXAMS = gql`
  query ChildExams($childId: ID!) {
    childExams(childId: $childId) {
      id
      name
      subject
      status
      startsAt
      expiresAt
      durationSeconds
      questionCount
      totalScore
      submittedAt
    }
  }
`;

export const CHILD_EXAM_RESULT = gql`
  query ChildExamResult($childId: ID!, $examId: ID!) {
    childExamResult(childId: $childId, examId: $examId) {
      examId
      examName
      score
      maxScore
      grade
      submittedAt
      durationSeconds
      questionResults {
        questionId
        questionContent
        questionType
        studentAnswer
        correctAnswer
        isCorrect
        isAnswered
        explanation
        maxScore
        earnedScore
      }
    }
  }
`;

export const CHILD_CLASSES = gql`
  query ChildClasses($childId: ID!) {
    childClasses(childId: $childId) {
      id
      name
      homeroomTeacher
      studentCount
      grade
      year
    }
  }
`;

export const CHILD_LEARNING_PATH = gql`
  query ChildLearningPath($childId: ID!) {
    childLearningPath(childId: $childId) {
      id
      name
      knowledgePointId
      status
      mastery
      dependencies
      recommendedOrder
      recommendation
    }
  }
`;

export const CURRENT_PARENT_DETAIL = gql`
  query CurrentParentDetail {
    currentUser {
      id
      email
      name
      roles
      permissions
      dataScope
      schoolId
    }
  }
`;

export const MY_NOTIFICATIONS = gql`
  query MyNotifications($unreadOnly: Boolean, $limit: Int) {
    myNotifications(unreadOnly: $unreadOnly, limit: $limit) {
      id
      childId
      eventType
      title
      body
      read
      createdAt
      actionUrl
      pinned
    }
  }
`;

export const MY_NOTIFICATION_PREFERENCES = gql`
  query MyNotificationPreferences {
    myNotificationPreferences {
      parentId
      preferences
      defaults
      updatedAt
    }
  }
`;

// ===== 变更 =====

export const MARK_AS_READ = gql`
  mutation MarkAsRead($notificationId: ID!) {
    markAsRead(notificationId: $notificationId) {
      id
      read
    }
  }
`;

export const MARK_ALL_AS_READ = gql`
  mutation MarkAllAsRead {
    markAllAsRead {
      count
    }
  }
`;

export const UPDATE_NOTIFICATION_PREFERENCES = gql`
  mutation UpdateNotificationPreferences(
    $parentId: ID!
    $preferences: JSON!
    $defaults: JSON!
  ) {
    updateNotificationPreferences(
      parentId: $parentId
      preferences: $preferences
      defaults: $defaults
    ) {
      parentId
      updatedAt
    }
  }
`;

export const SWITCH_CHILD = gql`
  mutation SwitchChild($childId: ID!) {
    switchChild(childId: $childId) {
      childId
      childName
      selectedAt
    }
  }
`;

// ===== 参考项目差距补齐：请假 / 报告卡 / 错题本 / 诊断 / 练习 / 课程 / 备课 / 选修 / 子女详情 =====

// ----- 请假 -----
export const CHILD_LEAVE_REQUESTS = gql`
  query ChildLeaveRequests($childId: ID!) {
    childLeaveRequests(childId: $childId) {
      id
      childId
      childName
      className
      type
      startDate
      endDate
      reason
      status
      submittedAt
      reviewedAt
      reviewerName
      reviewComment
    }
  }
`;

export const CREATE_LEAVE_REQUEST = gql`
  mutation CreateLeaveRequest($input: LeaveRequestInput!) {
    createLeaveRequest(input: $input) {
      id
      childId
      type
      startDate
      endDate
      reason
      status
      submittedAt
    }
  }
`;

// ----- 报告卡 -----
export const ACADEMIC_YEARS = gql`
  query AcademicYears {
    academicYears {
      id
      name
      startDate
      endDate
    }
  }
`;

export const CHILD_REPORT_CARD = gql`
  query ChildReportCard($childId: ID!, $academicYearId: ID!, $semester: Int!) {
    childReportCard(
      childId: $childId
      academicYearId: $academicYearId
      semester: $semester
    ) {
      childId
      childName
      className
      academicYearId
      academicYearName
      semester
      subjects {
        subject
        score
        maxScore
        gradeLevel
        classAverage
        rank
        classSize
        teacherComment
      }
      overallScore
      classRank
      classSize
      teacherComment
      headTeacherComment
      issuedAt
    }
  }
`;

// ----- 错题本 -----
export const CHILD_ERROR_BOOK_STATS = gql`
  query ChildErrorBookStats($childId: ID!) {
    childErrorBookStats(childId: $childId) {
      childId
      totalCount
      newCount
      learningCount
      masteredCount
      dueReviewCount
      masteredRate
    }
  }
`;

export const CHILD_TOP_WRONG_QUESTIONS = gql`
  query ChildTopWrongQuestions($childId: ID!, $limit: Int) {
    childTopWrongQuestions(childId: $childId, limit: $limit) {
      id
      questionContent
      subject
      knowledgePoint
      errorCount
      lastErrorAt
      masteryRate
    }
  }
`;

export const CHILD_WEAK_KPS = gql`
  query ChildWeakKps($childId: ID!, $limit: Int) {
    childWeakKps(childId: $childId, limit: $limit) {
      knowledgePointName
      subject
      errorCount
      masteryRate
    }
  }
`;

// ----- 诊断报告 -----
export const CHILD_MASTERY_SUMMARY = gql`
  query ChildMasterySummary($childId: ID!) {
    childMasterySummary(childId: $childId) {
      childId
      overallMastery
      subjectMastery {
        subject
        mastery
      }
      totalKps
      masteredKps
    }
  }
`;

export const CHILD_DIAGNOSTIC_REPORTS = gql`
  query ChildDiagnosticReports($childId: ID!) {
    childDiagnosticReports(childId: $childId) {
      id
      childId
      title
      summary
      status
      createdAt
      publishedAt
      masteryScore
      subjects {
        subject
        masteryLevel
        strengths
        weaknesses
        recommendation
      }
    }
  }
`;

// ----- 练习统计 -----
export const CHILD_PRACTICE_STATS = gql`
  query ChildPracticeStats($childId: ID!) {
    childPracticeStats(childId: $childId) {
      childId
      totalSessions
      completedSessions
      totalQuestionsAnswered
      overallAccuracy
    }
  }
`;

export const CHILD_PRACTICE_SESSIONS = gql`
  query ChildPracticeSessions($childId: ID!, $limit: Int) {
    childPracticeSessions(childId: $childId, limit: $limit) {
      id
      childId
      subject
      startedAt
      completedAt
      questionCount
      correctCount
      accuracy
      durationSeconds
      knowledgePoints
    }
  }
`;

// ----- 课程计划 -----
export const CHILD_COURSE_PLANS = gql`
  query ChildCoursePlans($childId: ID!) {
    childCoursePlans(childId: $childId) {
      id
      title
      description
      subject
      className
      teacherName
      startDate
      endDate
      status
      chapterCount
    }
  }
`;

export const CHILD_COURSE_PLAN_DETAIL = gql`
  query ChildCoursePlanDetail($childId: ID!, $planId: ID!) {
    childCoursePlanDetail(childId: $childId, planId: $planId) {
      id
      title
      description
      subject
      className
      teacherName
      startDate
      endDate
      status
      chapterCount
      chapters {
        id
        title
        description
        sortOrder
        lessonCount
        estimatedHours
      }
    }
  }
`;

// ----- 备课计划 -----
export const CHILD_LESSON_PLANS = gql`
  query ChildLessonPlans($childId: ID!, $subject: String) {
    childLessonPlans(childId: $childId, subject: $subject) {
      id
      title
      subject
      className
      teacherName
      textbookTitle
      chapterTitle
      status
      publishedAt
      estimatedMinutes
    }
  }
`;

export const CHILD_LESSON_PLAN_DETAIL = gql`
  query ChildLessonPlanDetail($childId: ID!, $planId: ID!) {
    childLessonPlanDetail(childId: $childId, planId: $planId) {
      id
      title
      subject
      className
      teacherName
      textbookTitle
      chapterTitle
      status
      publishedAt
      estimatedMinutes
      objectives
      keyPoints
      difficultPoints
      content
      homeworkDescription
    }
  }
`;

// ----- 选修课 -----
export const CHILD_ELECTIVE = gql`
  query ChildElective($childId: ID!) {
    childElective(childId: $childId) {
      id
      childId
      courseName
      courseCode
      teacherName
      category
      credits
      schedule
      status
      enrolledAt
      score
    }
  }
`;

// ----- 子女详情聚合 -----
export const CHILD_DETAIL = gql`
  query ChildDetail($childId: ID!) {
    childDetail(childId: $childId) {
      childId
      basicInfo {
        name
        avatar
        grade
        className
        schoolName
        relation
      }
      todaySchedule {
        id
        dayOfWeek
        period
        subject
        teacherName
        classroom
        startTime
        endTime
      }
      weeklySchedule {
        id
        dayOfWeek
        period
        subject
        teacherName
        classroom
        startTime
        endTime
      }
      homeworkSummary {
        pendingCount
        overdueCount
        submittedCount
        gradedCount
      }
      gradeSummary {
        avgScore
        classRank
        classSize
        trend
      }
      examResults {
        upcoming
        completed
        avgScore
      }
    }
  }
`;

// ----- 成长档案（班级均对比线）-----
export const CHILD_GROWTH_ARCHIVE = gql`
  query ChildGrowthArchive($childId: ID!, $subject: String) {
    childGrowthArchive(childId: $childId, subject: $subject) {
      childId
      subject
      dataPoints {
        date
        studentScore
        classAverage
      }
    }
  }
`;

// ----- 导出成绩 -----
export const EXPORT_CHILD_GRADES = gql`
  mutation ExportChildGrades($childId: ID!, $subject: String) {
    exportChildGrades(childId: $childId, subject: $subject) {
      downloadUrl
      expiresAt
    }
  }
`;
