import { createApi, fetchBaseQuery, FetchBaseQueryError } from '@reduxjs/toolkit/query/react';
import { Lead, LeadFormData, LeadResponse } from '../../types/lead';

export const leadApi = createApi({
  reducerPath: 'leadApi',
  baseQuery: fetchBaseQuery({ 
    baseUrl: process.env.REACT_APP_API_URL || '/api',
    credentials: 'include',
    prepareHeaders: (headers) => {
      headers.set('Content-Type', 'application/json');
      const token = localStorage.getItem('auth_token');
      if (token) {
        headers.set('Authorization', `Bearer ${token}`);
      }
      return headers;
    }
  }),
  tagTypes: ['Lead'],
  endpoints: (builder) => ({
    getLeads: builder.query<Lead[], void>({
      query: () => 'leads',
      providesTags: ['Lead'],
      transformResponse: (response: { data: Lead[] }) => response.data,
      transformErrorResponse: (response: FetchBaseQueryError) => {
        return {
          status: response.status,
          message: 'Failed to fetch leads'
        };
      }
    }),
    addLead: builder.mutation<LeadResponse, LeadFormData>({
      query: (lead) => ({
        url: 'leads',
        method: 'POST',
        body: lead,
      }),
      invalidatesTags: ['Lead'],
      transformErrorResponse: (response: FetchBaseQueryError) => {
        return {
          status: response.status,
          message: 'Failed to add lead'
        };
      }
    }),
    updateLead: builder.mutation<LeadResponse, Partial<Lead> & Pick<Lead, 'id'>>({ 
      query: ({ id, ...patch }) => ({
        url: `leads/${id}`,
        method: 'PATCH',
        body: patch,
      }),
      invalidatesTags: ['Lead'],
      transformErrorResponse: (response: FetchBaseQueryError) => {
        return {
          status: response.status,
          message: 'Failed to update lead'
        };
      }
    })
  })
});

export const { 
  useGetLeadsQuery,
  useAddLeadMutation,
  useUpdateLeadMutation
} = leadApi;