// useExportChildGrades：导出子女成绩
// 依据：02-architecture-design.md §4.2 GraphQL 接入
// - mutation EXPORT_CHILD_GRADES，返回下载链接 + 过期时间
// - 支持可选 subject 参数（按学科筛选导出）

"use client";

import { useState } from "react";
import { useMutation, type CombinedError } from "urql";
import { EXPORT_CHILD_GRADES } from "@/lib/graphql/operations";
import type { ExportResult } from "@/types";

interface ExportChildGradesResponse {
  exportChildGrades: ExportResult;
}

interface ExportChildGradesInput {
  childId: string;
  subject?: string;
}

export function useExportChildGrades(): {
  exportGrades: (
    input: ExportChildGradesInput,
  ) => Promise<{ success: boolean; data?: ExportResult; error?: CombinedError }>;
  loading: boolean;
  error: CombinedError | undefined;
} {
  const [, mutate] = useMutation<ExportChildGradesResponse>(
    EXPORT_CHILD_GRADES,
  );
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<CombinedError | undefined>(undefined);

  const exportGrades = async (
    input: ExportChildGradesInput,
  ): Promise<{
    success: boolean;
    data?: ExportResult;
    error?: CombinedError;
  }> => {
    setLoading(true);
    setError(undefined);
    const result = await mutate({
      childId: input.childId,
      subject: input.subject ?? null,
    });
    setLoading(false);
    if (result.error) {
      setError(result.error);
      return { success: false, error: result.error };
    }
    return { success: true, data: result.data?.exportChildGrades };
  };

  return { exportGrades, loading, error };
}
