import type { BaseQueryFn } from '@reduxjs/toolkit/query';
import type { AxiosRequestConfig } from 'axios';

import Api from '@/api';
import { rejectPayload, type ApiErrorPayload } from '@/utils/api';

export interface AxiosBaseQueryArgs {
  data?: unknown;
  headers?: AxiosRequestConfig['headers'];
  method?: 'delete' | 'get' | 'post' | 'put';
  params?: AxiosRequestConfig['params'];
  url: string;
}

// RTK Query over the shared axios wrapper, so its auth and Cf-Html-Encode
// interceptors still apply and failures keep the ApiErrorPayload shape.
export const axiosBaseQuery =
  (): BaseQueryFn<AxiosBaseQueryArgs, unknown, ApiErrorPayload> =>
  async ({ url, method = 'get', data, params, headers }, { signal }) => {
    const config: AxiosRequestConfig = { params, signal, headers };
    try {
      switch (method) {
        case 'post':
          return { data: (await Api.post(url, data, config)).data };
        case 'put':
          return { data: (await Api.put(url, data, config)).data };
        case 'delete':
          return { data: (await Api.delete(url, data)).data };
        default:
          return { data: (await Api.get(url, config)).data };
      }
    } catch (error) {
      return { error: rejectPayload(error) };
    }
  };
