import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { getConfigValue } from '@brojs/cli';

import { Master } from '../../models/api/master';

type SuccessResponse<Body> = {
  success: true;
  body: Body;
};

type ErrorResponse = {
  success: false;
  message: string;
};

type BaseResponse<Body> = SuccessResponse<Body> | ErrorResponse;

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: getConfigValue('dry-wash.api') }),
  tagTypes: ['Masters'],
  endpoints: (builder) => ({
    getMasters: builder.query<Master[], void>({
      query: () => ({ url: '/arm/masters' }),
      transformResponse: (response: BaseResponse<Master[]>) => {
        if (response.success) {
          return response.body;
        }
      },
      providesTags: ['Masters'],
    }),
    addMaster: builder.mutation<void, Pick<Master, 'name' | 'phone'>>({
      query: (master) => ({
        url: '/arm/masters',
        method: 'POST',
        body: master,
      }),
      invalidatesTags: ['Masters'],
    }),
  }),
});
