import api from "../axios";
import { API_ENDPOINTS } from "../endpoints";
import { ApiResponse } from "../types";
import {
  CreateCustomerCredentials,
  CustomerListResponseSchema,
  TAssignCustomerToCompanyCredentials,
  TCustomersListResponse,
} from "../types/Customers";

export const customersService = {
  getCustomers: async (
    params?: Record<string, any>,
  ): Promise<ApiResponse<TCustomersListResponse>> => {
    try {
      const response = await api.get(API_ENDPOINTS.CUSTOMERS.READ_ALL, {
        params,
      });
      return response.data
    } catch (error) {
      console.error("ERROR caught in Customers Services Read all:", error);
      throw error;
    }
  },
  deleteCustomer: async (id: string) => {
    try {
      return (await api.delete(API_ENDPOINTS.CUSTOMERS.DELETE(id))).data;
    } catch (error) {
      console.error("ERROR caught in Customers Services Delete:", error);
      throw error;
    }
  },
  createCustomer: async (credentials: CreateCustomerCredentials) => {
    try {
      return (await api.post(API_ENDPOINTS.CUSTOMERS.CREATE, credentials)).data;
    } catch (error) {
      console.error("ERROR caught in Customers Services Create:", error);
      throw error;
    }
  },
  updateCustomer: async ({
    id,
    credentials,
  }: {
    id: string;
    credentials: CreateCustomerCredentials;
  }) => {
    try {
      return (await api.put(API_ENDPOINTS.CUSTOMERS.UPDATE(id), credentials))
        .data;
    } catch (error) {
      console.error("ERROR caught in Customers Services Update:", error);
      throw error;
    }
  },
  customerDetails: async (id: string) => {
    const response = await api.get(API_ENDPOINTS.CUSTOMERS.DETAILS(id));
    return response.data;
  },
  assignCompanyToCustomer: async ({
    credentials,
    id,
  }: {
    id: string;
    credentials: TAssignCustomerToCompanyCredentials;
  }): Promise<any> => {
    try {
      return (
        await api.post(
          API_ENDPOINTS.CUSTOMERS.ASSIGN_COMPANY_TO_CUSTOMER(id),
          credentials,
        )
      ).data;
    } catch (error) {
      console.error(
        "ERROR caught in Customers Service => Assign company to customer",
        error,
      );
      throw error;
    }
  },
};
