import axios from 'axios';
import { API_URL } from '@/shared/api/urls';
import { resultify } from '@/shared/lib/resultify';
import { CBDCAxiosError } from '@/shared/@types/error';
import { 
  CodesSelectParams,
  CodesSelectGetResponse,
  CodesSelectPostResponse,
} from '../model/types';
import { 
  useMutation,
  UseMutationOptions
} from '@tanstack/react-query';

export const codesSelect = ({
  codeCl,
  colNm,
  code1,
  code2,
  useCl,
  method
}: CodesSelectParams) => {
  if(method === 'get'){
    return resultify(
      axios.get<CodesSelectGetResponse>(API_URL.codesSelect()),
    );
  }
  else{
    return resultify(
      axios.post<CodesSelectPostResponse>(API_URL.codesSelect(), {
        codeCl,
        colNm,
        code1,
        code2,
        useCl
      }),
    );
  }
};

export const useCodesSelectMutation = (options?: UseMutationOptions<CodesSelectGetResponse | CodesSelectPostResponse, CBDCAxiosError, CodesSelectParams>) => {
  const mutation = useMutation<CodesSelectGetResponse | CodesSelectPostResponse, CBDCAxiosError, CodesSelectParams>({
    ...options,
    mutationFn: ({
      codeCl,
      colNm,
      code1,
      code2,
      useCl,
      method
    }: CodesSelectParams) => codesSelect({
      codeCl,
      colNm,
      code1,
      code2,
      useCl,
      method
    }),
  });

  return {
    ...mutation,
  };
};
