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

export const codesSelect = ({
  codeCl,
  colNm,
  code1,
  code2,
  useCl,
  method
}: CodesSelectParams) => {
  if(method === 'get'){
    return resultify(
      axios.get<CodesSelectGetResponse & CodesSelectPostResponse>(API_URL.codesSelect()),
    );
  }
  else{
    let headerOptions = {
      menuId: 0,
      apiType: 'SELECT'
    };
    let options = {
      headers: {
        'X-User-Agent': getHeaderUserAgent(headerOptions)
      }
    };
    return resultify(
      axios.post<CodesSelectGetResponse & CodesSelectPostResponse>(API_URL.codesSelect(), {
        codeCl,
        colNm,
        code1,
        code2,
        useCl
      }, options),
    );
  }
};

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

  return {
    ...mutation,
  };
};
