import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { has } from 'lodash';
import { toast } from 'sonner';

const baseQuery = fetchBaseQuery({
  baseUrl: process.env.NEXT_PUBLIC_API_URL,
});

export const TAGS = {
  STOCKS: 'stocks',
  GAS_STATIONS: 'gas-stations',
  VACANCIES: 'vacancies',
  PARTNERS: 'partners',
  CERTIFICATES: 'certificates',
  CHARITY: 'charity',
} as const;

export const baseAPI = createApi({
  reducerPath: 'baseAPI',
  baseQuery: async (args, api, extraOptions) => {
    const result = await baseQuery(args, api, extraOptions);

    if (result.error) {
      switch (result.error.status) {
        case 401:
          if (
            has(result.error.data, 'error') &&
            result.error.data.error === 'Credentials error'
          ) {
            toast.error('Login credentials error');
            break;
          }

          window.location.href = '/login';
          break;

        case 500:
          toast.error('Server error, please try later');
          break;

        default:
          break;
      }
    }
    return result;
  },
  tagTypes: Object.values(TAGS),
  endpoints: () => ({}),
});
