/**
 * GraphQL client + operations
 *
 * 仲裁：ARB-001 admin 命名空间 GraphQL + ARB-002 复用 Shell GraphQL client 单例
 * 端点：POST /api/admin/graphql（经 api-gateway 代理到 teacher-bff admin 命名空间）
 */
import { createClient, fetchExchange, type Client } from "@urql/core";

const GRAPHQL_ENDPOINT = "/api/admin/graphql";

/** 创建 urql GraphQL client（standalone 模式自建，MF 模式复用 Shell 单例） */
export function createGraphQLClient(): Client {
  return createClient({
    url: GRAPHQL_ENDPOINT,
    exchanges: [fetchExchange],
    fetchOptions: () => {
      const token =
        typeof window !== "undefined"
          ? localStorage.getItem("edu_access_token")
          : null;
      return token ? { headers: { Authorization: `Bearer ${token}` } } : {};
    },
  });
}

// ─── GraphQL Operations（contract §2.4） ───────────────────────────

export const CURRENT_USER_QUERY = `
  query CurrentUser {
    currentUser {
      id
      email
      name
      roles
      permissions
      dataScope
      schoolId
      schoolName
    }
  }
` as const;

export const ADMIN_USERS_QUERY = `
  query AdminUsers($filter: AdminUserFilterInput) {
    adminUsers(filter: $filter) {
      items {
        id
        email
        name
        roles { id name code }
        status
        dataScope
        organizationId
        schoolName
        lastLoginAt
        createdAt
        updatedAt
      }
      total
      page
      pageSize
      hasNext
    }
  }
` as const;

export const ADMIN_USER_QUERY = `
  query AdminUser($id: ID!) {
    adminUser(id: $id) {
      id
      email
      name
      roles { id name code }
      status
      dataScope
      organizationId
      schoolName
      lastLoginAt
      createdAt
      updatedAt
    }
  }
` as const;

export const CREATE_USER_MUTATION = `
  mutation CreateUser($input: CreateUserInput!) {
    createUser(input: $input) {
      id
      email
      name
      status
    }
  }
` as const;

export const UPDATE_USER_MUTATION = `
  mutation UpdateUser($id: ID!, $input: UpdateUserInput!) {
    updateUser(id: $id, input: $input) {
      id
      email
      name
      status
    }
  }
` as const;

export const TOGGLE_USER_STATUS_MUTATION = `
  mutation ToggleUserStatus($id: ID!, $status: String!) {
    toggleUserStatus(id: $id, status: $status) {
      id
      status
    }
  }
` as const;

export const ADMIN_ROLES_QUERY = `
  query AdminRoles {
    adminRoles {
      id
      name
      code
      description
      permissions { id code name resource action }
      userCount
      dataScope
      isSystem
      createdAt
      updatedAt
    }
  }
` as const;

export const CREATE_ROLE_MUTATION = `
  mutation CreateRole($input: CreateRoleInput!) {
    createRole(input: $input) { id name code }
  }
` as const;

export const UPDATE_ROLE_PERMISSIONS_MUTATION = `
  mutation UpdateRolePermissions($roleId: ID!, $permissionCodes: [String!]!) {
    updateRolePermissions(roleId: $roleId, permissionCodes: $permissionCodes) {
      id
      permissions { id code }
    }
  }
` as const;

export const ADMIN_PERMISSIONS_QUERY = `
  query AdminPermissions {
    adminPermissions {
      id
      code
      name
      description
      resource
      action
      isSystem
    }
  }
` as const;

export const ADMIN_VIEWPORTS_QUERY = `
  query AdminViewports($scope: String) {
    adminViewports(scope: $scope) {
      id
      key
      label
      route
      icon
      sortOrder
      requiredPermission
      scope
      isVisible
    }
  }
` as const;

export const UPDATE_VIEWPORT_MUTATION = `
  mutation UpdateViewport($id: ID!, $input: UpdateViewportInput!) {
    updateViewport(id: $id, input: $input) {
      id
      key
      label
      sortOrder
      isVisible
    }
  }
` as const;

export const ADMIN_ORGANIZATION_QUERY = `
  query AdminOrganization($parentId: ID) {
    adminOrganization(parentId: $parentId) {
      id
      name
      type
      parentId
      childrenCount
      sortOrder
    }
  }
` as const;

export const ADMIN_CLASSES_QUERY = `
  query AdminClasses($filter: AdminClassFilterInput) {
    adminClasses(filter: $filter) {
      items {
        id
        name
        gradeName
        schoolName
        headTeacherName
        studentCount
        createdAt
      }
      total
      page
      pageSize
      hasNext
    }
  }
` as const;

export const ADMIN_TEACHERS_QUERY = `
  query AdminTeachers($filter: AdminTeacherFilterInput) {
    adminTeachers(filter: $filter) {
      items {
        id
        email
        name
        schoolName
        subjects
        classCount
        status
        lastLoginAt
      }
      total
      page
      pageSize
      hasNext
    }
  }
` as const;

export const ADMIN_STUDENTS_QUERY = `
  query AdminStudents($filter: AdminStudentFilterInput) {
    adminStudents(filter: $filter) {
      items {
        id
        email
        name
        className
        gradeName
        schoolName
        guardianName
        guardianPhone
        status
      }
      total
      page
      pageSize
      hasNext
    }
  }
` as const;

export const AUDIT_LOGS_QUERY = `
  query AuditLogs($filter: AuditLogFilterInput) {
    auditLogs(filter: $filter) {
      items {
        id
        eventId
        occurredAt
        actorUserId
        actorName
        action
        resourceType
        resourceId
        ip
        userAgent
        beforeState
        afterState
        traceId
      }
      total
      page
      pageSize
      hasNext
    }
  }
` as const;

export const ADMIN_DASHBOARD_QUERY = `
  query AdminDashboard {
    adminDashboard {
      totalTeachers
      totalStudents
      totalClasses
      totalSchools
      schoolAvgScore
      activeUsersToday
      auditEventsToday
      trend { date teachers students avgScore }
      serviceHealth { serviceName status latencyMs }
    }
  }
` as const;

export const SYSTEM_SETTINGS_QUERY = `
  query SystemSettings {
    systemSettings {
      schoolName
      schoolCode
      academicYear
      semester
      contactEmail
      contactPhone
      address
      timezone
      locale
    }
  }
` as const;

export const UPDATE_SYSTEM_SETTINGS_MUTATION = `
  mutation UpdateSystemSettings($input: SystemSettingsInput!) {
    updateSystemSettings(input: $input) {
      schoolName
      schoolCode
      academicYear
      semester
    }
  }
` as const;

// ─── 审计日志子模块 ─────────────────────────────────────────────────

export const AUDIT_OVERVIEW_STATS_QUERY = `
  query AuditOverviewStats {
    auditOverviewStats {
      totalEvents
      todayEvents
      uniqueActors
      failedActions
      topActions { action count }
      topResources { resource count }
    }
  }
` as const;

export const AUDIT_TREND_QUERY = `
  query AuditTrend($days: Int) {
    auditTrend(days: $days) {
      date
      count
      action
    }
  }
` as const;

export const DATA_CHANGE_LOGS_QUERY = `
  query DataChangeLogs($filter: DataChangeLogFilterInput) {
    dataChangeLogs(filter: $filter) {
      items {
        id
        occurredAt
        actorUserId
        actorName
        tableName
        action
        recordId
        beforeState
        afterState
        ip
      }
      total
      page
      pageSize
      hasNext
    }
  }
` as const;

export const LOGIN_LOGS_QUERY = `
  query LoginLogs($filter: LoginLogFilterInput) {
    loginLogs(filter: $filter) {
      items {
        id
        occurredAt
        userId
        userName
        action
        status
        ip
        userAgent
        failureReason
      }
      total
      page
      pageSize
      hasNext
    }
  }
` as const;

// ─── 学校组织管理细化 ──────────────────────────────────────────────

export const ADMIN_SCHOOLS_QUERY = `
  query AdminSchools {
    adminSchools {
      id
      name
      code
      address
      contactPhone
      contactEmail
      principalName
      gradeCount
      classCount
      studentCount
      teacherCount
      createdAt
    }
  }
` as const;

export const ADMIN_GRADES_QUERY = `
  query AdminGrades($schoolId: ID) {
    adminGrades(schoolId: $schoolId) {
      id
      name
      schoolId
      schoolName
      directorName
      classCount
      studentCount
      sortOrder
      createdAt
    }
  }
` as const;

export const ADMIN_GRADE_INSIGHTS_QUERY = `
  query AdminGradeInsights($gradeId: ID!) {
    adminGradeInsights(gradeId: $gradeId) {
      gradeId
      gradeName
      schoolWideSummary {
        totalStudents
        totalClasses
        avgScore
        passingRate
      }
      homeworkTimeline {
        homeworkId
        title
        className
        avgScore
        submittedCount
        totalCount
        dueDate
      }
      classRankings {
        classId
        className
        avgScore
        rank
        delta
      }
    }
  }
` as const;

export const ADMIN_DEPARTMENTS_QUERY = `
  query AdminDepartments($schoolId: ID) {
    adminDepartments(schoolId: $schoolId) {
      id
      name
      schoolId
      schoolName
      leaderName
      memberCount
      subject
      createdAt
    }
  }
` as const;

export const ADMIN_ACADEMIC_YEARS_QUERY = `
  query AdminAcademicYears {
    adminAcademicYears {
      id
      name
      startDate
      endDate
      firstSemesterStart
      firstSemesterEnd
      secondSemesterStart
      secondSemesterEnd
      isCurrent
      createdAt
    }
  }
` as const;

// ─── 公告管理 ───────────────────────────────────────────────────────

export const ADMIN_ANNOUNCEMENTS_QUERY = `
  query AdminAnnouncements($filter: AnnouncementFilterInput) {
    adminAnnouncements(filter: $filter) {
      items {
        id
        title
        content
        status
        audience
        authorName
        isPinned
        readCount
        totalCount
        publishedAt
        createdAt
        updatedAt
      }
      total
      page
      pageSize
      hasNext
    }
  }
` as const;

export const CREATE_ANNOUNCEMENT_MUTATION = `
  mutation CreateAnnouncement($input: CreateAnnouncementInput!) {
    createAnnouncement(input: $input) {
      id
      title
      status
    }
  }
` as const;

export const PUBLISH_ANNOUNCEMENT_MUTATION = `
  mutation PublishAnnouncement($id: ID!) {
    publishAnnouncement(id: $id) { id status }
  }
` as const;

export const ARCHIVE_ANNOUNCEMENT_MUTATION = `
  mutation ArchiveAnnouncement($id: ID!) {
    archiveAnnouncement(id: $id) { id status }
  }
` as const;

export const TOGGLE_ANNOUNCEMENT_PIN_MUTATION = `
  mutation ToggleAnnouncementPin($id: ID!) {
    toggleAnnouncementPin(id: $id) { id isPinned }
  }
` as const;

// ─── 邀请码管理 ─────────────────────────────────────────────────────

export const ADMIN_INVITATION_CODES_QUERY = `
  query AdminInvitationCodes($filter: InvitationCodeFilterInput) {
    adminInvitationCodes(filter: $filter) {
      items {
        id
        code
        status
        roleId
        roleName
        classId
        className
        email
        batchId
        usedBy
        usedByName
        usedAt
        createdAt
        expiresAt
      }
      total
      page
      pageSize
      hasNext
    }
  }
` as const;

export const GENERATE_INVITATION_CODES_MUTATION = `
  mutation GenerateInvitationCodes($input: GenerateInvitationCodesInput!) {
    generateInvitationCodes(input: $input) {
      codes
      batchId
    }
  }
` as const;

export const DELETE_INVITATION_CODES_MUTATION = `
  mutation DeleteInvitationCodes($ids: [ID!]!) {
    deleteInvitationCodes(ids: $ids)
  }
` as const;

// ─── 文件管理 ───────────────────────────────────────────────────────

export const ADMIN_FILES_QUERY = `
  query AdminFiles($filter: FileFilterInput) {
    adminFiles(filter: $filter) {
      items {
        id
        filename
        mimeType
        size
        url
        entityType
        entityId
        uploadedByName
        createdAt
      }
      total
      page
      pageSize
      hasNext
    }
  }
` as const;

export const ADMIN_FILE_STATS_QUERY = `
  query AdminFileStats {
    adminFileStats {
      totalFiles
      totalSize
      byMimeType { mimeType count size }
      byEntityType { entityType count }
    }
  }
` as const;

export const DELETE_FILES_MUTATION = `
  mutation DeleteFiles($ids: [ID!]!) {
    deleteFiles(ids: $ids)
  }
` as const;

// ─── AI 配置 ─────────────────────────────────────────────────────────

export const AI_PROVIDERS_QUERY = `
  query AiProviders {
    aiProviders {
      id
      name
      type
      isPublic
      isActive
      model
      apiBase
      createdBy
      createdAt
    }
  }
` as const;

export const UPDATE_AI_PROVIDER_MUTATION = `
  mutation UpdateAiProvider($id: ID!, $input: UpdateAiProviderInput!) {
    updateAiProvider(id: $id, input: $input) {
      id
      isActive
    }
  }
` as const;

export const AI_USAGE_QUERY = `
  query AiUsage {
    aiUsage {
      totalRequests
      totalTokens
      totalCost
      byProvider {
        providerName
        requests
        tokens
        cost
      }
      byDay {
        date
        requests
        tokens
      }
    }
  }
` as const;
