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

import { Master, OrderArm } from '../../models/api';

import { extractBodyFromResponse } from './utils';

export type UpdateMasterPayload = Required<Pick<Master, 'id'>> &
  Partial<Omit<Master, 'id'>>;

type UpdateOrderProps = Required<Pick<OrderArm, 'id'>> &
  Partial<Pick<OrderArm, 'status' | 'notes'>> & {
    master?: string;
  };

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({
    baseUrl: new URL(getConfigValue('dry-wash.api'), location.origin).href,
  }),
  tagTypes: ['Masters', 'Orders'],
  endpoints: (builder) => ({
    getMasters: builder.query<Master[], void>({
      query: () => ({ url: '/arm/masters' }),
      transformResponse: extractBodyFromResponse<Master[]>,
      providesTags: ['Masters'],
    }),
    updateOrders: builder.mutation<void, UpdateOrderProps>({
      query: ({ id, status, notes, master }) => ({
        url: `/order/${id}`,
        method: 'PATCH',
        body: { status, notes, master },
      }),
      invalidatesTags: ['Orders'],
    }),
    getOrders: builder.query<OrderArm[], { date: Date }>({
      query: ({ date }) => {
        const startDate = dayjs(date).startOf('day').toISOString();
        const endDate = dayjs(date).endOf('day').toISOString();
        return {
          url: '/arm/orders',
          method: 'POST',
          body: { startDate, endDate },
        };
      },
      transformResponse: extractBodyFromResponse<OrderArm[]>,
      providesTags: ['Orders'],
    }),

    addMaster: builder.mutation<void, Pick<Master, 'name' | 'phone'>>({
      query: (master) => ({
        url: '/arm/masters',
        method: 'POST',
        body: master,
      }),
      invalidatesTags: ['Masters'],
    }),
    deleteMaster: builder.mutation<void, { id: string }>({
      query: ({ id }) => ({
        url: `/arm/masters/${id}`,
        method: 'DELETE',
      }),
      invalidatesTags: ['Masters'],
    }),
    updateMaster: builder.mutation<void, UpdateMasterPayload>({
      query: ({ id, name, phone }) => ({
        url: `/arm/masters/${id}`,
        method: 'PATCH',
        body: { name, phone },
      }),
      invalidatesTags: ['Masters'],
    }),
  }),
});

export const {
  useGetMastersQuery,
  useAddMasterMutation,
  useDeleteMasterMutation,
  useUpdateMasterMutation,
  useGetOrdersQuery,
  useUpdateOrdersMutation,
} = api;
