/**
 * 学校组织管理 Hooks
 *
 * contract §2.4：adminSchools / adminGrades / adminGradeInsights /
 * adminDepartments / adminAcademicYears
 */
import { useGraphQuery } from "./use-graphql";
import {
  ADMIN_SCHOOLS_QUERY,
  ADMIN_GRADES_QUERY,
  ADMIN_GRADE_INSIGHTS_QUERY,
  ADMIN_DEPARTMENTS_QUERY,
  ADMIN_ACADEMIC_YEARS_QUERY,
} from "@/lib/graphql-client";
import type {
  SchoolViewModel,
  GradeViewModel,
  GradeInsightsViewModel,
  DepartmentViewModel,
  AcademicYearViewModel,
} from "@/types/view-models";

interface AdminSchoolsResponse {
  adminSchools: SchoolViewModel[];
}

interface AdminGradesResponse {
  adminGrades: GradeViewModel[];
}

interface AdminGradeInsightsResponse {
  adminGradeInsights: GradeInsightsViewModel;
}

interface AdminDepartmentsResponse {
  adminDepartments: DepartmentViewModel[];
}

interface AdminAcademicYearsResponse {
  adminAcademicYears: AcademicYearViewModel[];
}

/** 学校列表 */
export function useSchools() {
  const result = useGraphQuery<AdminSchoolsResponse>(ADMIN_SCHOOLS_QUERY);
  return {
    ...result,
    data: result.data?.adminSchools ?? [],
  };
}

/** 年级列表（可按学校筛选） */
export function useGrades(schoolId?: string) {
  const variables = schoolId ? { schoolId } : {};
  const result = useGraphQuery<AdminGradesResponse>(
    ADMIN_GRADES_QUERY,
    variables,
  );
  return {
    ...result,
    data: result.data?.adminGrades ?? [],
  };
}

/** 年级洞察（按年级 ID） */
export function useGradeInsights(gradeId: string | null | undefined) {
  const result = useGraphQuery<AdminGradeInsightsResponse>(
    ADMIN_GRADE_INSIGHTS_QUERY,
    gradeId ? { gradeId } : {},
  );
  return {
    ...result,
    data: result.data?.adminGradeInsights ?? null,
  };
}

/** 部门/教研组列表（可按学校筛选） */
export function useDepartments(schoolId?: string) {
  const variables = schoolId ? { schoolId } : {};
  const result = useGraphQuery<AdminDepartmentsResponse>(
    ADMIN_DEPARTMENTS_QUERY,
    variables,
  );
  return {
    ...result,
    data: result.data?.adminDepartments ?? [],
  };
}

/** 学年/学期列表 */
export function useAcademicYears() {
  const result = useGraphQuery<AdminAcademicYearsResponse>(
    ADMIN_ACADEMIC_YEARS_QUERY,
  );
  return {
    ...result,
    data: result.data?.adminAcademicYears ?? [],
  };
}
