// useCreateLeaveRequest：提交请假申请
// 依据：02-architecture-design.md §4.2 GraphQL 接入

"use client";

import { useState } from "react";
import { useMutation, type CombinedError } from "urql";
import { CREATE_LEAVE_REQUEST } from "@/lib/graphql/operations";
import type { LeaveRequest, LeaveRequestInput } from "@/types";

interface CreateLeaveRequestResponse {
  createLeaveRequest: LeaveRequest;
}

export function useCreateLeaveRequest(): {
  createLeave: (
    input: LeaveRequestInput,
  ) => Promise<{ success: boolean; error?: CombinedError }>;
  loading: boolean;
  error: CombinedError | undefined;
} {
  const [, mutate] = useMutation<CreateLeaveRequestResponse>(
    CREATE_LEAVE_REQUEST,
  );
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<CombinedError | undefined>(undefined);

  const createLeave = async (
    input: LeaveRequestInput,
  ): Promise<{ success: boolean; error?: CombinedError }> => {
    setLoading(true);
    setError(undefined);
    const result = await mutate({ input });
    setLoading(false);
    if (result.error) {
      setError(result.error);
      return { success: false, error: result.error };
    }
    return { success: true };
  };

  return { createLeave, loading, error };
}
