import axios from 'axios';
import { API_URL_USER } from '@/shared/api/api-url-user';
import { NiceAxiosError } from '@/shared/@types/error';
import {
  UserCreateParams,
  UserCreateResponse
} from '../model/types';

interface UserCreateMutationResponse {
  status: boolean;
  data?: UserCreateResponse;
  error?: {
    root: string;
    errKey: string;
    code: string;
    message: string;
    timestamp: string;
    details: Record<string, string>;
  };
}

import {
  useMutation,
  UseMutationOptions
} from '@tanstack/react-query';
import { getHeaderUserAgent } from '@/shared/constants/url';

export const userCreate = async (params: UserCreateParams): Promise<UserCreateMutationResponse> => {
  let headerOptions = {
    menuId: 45,
    apiType: 'INSERT'
  };
  let options = {
    headers: {
      'X-User-Agent': getHeaderUserAgent(headerOptions)
    }
  };
  try {
    const response = await axios.post<UserCreateResponse>(API_URL_USER.userCreate(), params, options);
    return { status: true, data: response.data };
  } catch (error: any) {
    return {
      status: false,
      error: {
        root: 'USER_CREATE',
        errKey: error.response?.data?.errKey || 'UNKNOWN_ERROR',
        code: error.response?.status?.toString() || '500',
        message: error.response?.data?.message || error.message || 'Unknown error',
        timestamp: new Date().toISOString(),
        details: error.response?.data?.details || {}
      }
    };
  }
};

export const useUserCreateMutation = (options?: UseMutationOptions<UserCreateMutationResponse, NiceAxiosError, UserCreateParams>) => {
  const mutation = useMutation<UserCreateMutationResponse, NiceAxiosError, UserCreateParams>({
    ...options,
    mutationFn: (params: UserCreateParams) => userCreate(params),
  });

  return {
    ...mutation,
  };
};
