import { apiClient } from '@/lib/api-client';
import type {
  CustomerContactMutationPayload,
  CustomerContactsResponse,
  CustomerDetailResponse,
  CustomerFilters,
  CustomerListResponse,
  CustomerMutationPayload,
  MutationSuccessResponse
} from './types';

export async function getCustomers(filters: CustomerFilters): Promise<CustomerListResponse> {
  const searchParams = new URLSearchParams();

  if (filters.page) searchParams.set('page', String(filters.page));
  if (filters.limit) searchParams.set('limit', String(filters.limit));
  if (filters.search) searchParams.set('search', filters.search);
  if (filters.customerStatus) searchParams.set('customerStatus', filters.customerStatus);
  if (filters.customerType) searchParams.set('customerType', filters.customerType);
  if (filters.branch) searchParams.set('branch', filters.branch);
  if (filters.sort) searchParams.set('sort', filters.sort);

  const query = searchParams.toString();

  return apiClient<CustomerListResponse>(`/crm/customers${query ? `?${query}` : ''}`);
}

export async function getCustomerById(id: string): Promise<CustomerDetailResponse> {
  return apiClient<CustomerDetailResponse>(`/crm/customers/${id}`);
}

export async function createCustomer(data: CustomerMutationPayload) {
  return apiClient<{ success: boolean; message: string }>('/crm/customers', {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

export async function updateCustomer(id: string, data: CustomerMutationPayload) {
  return apiClient<{ success: boolean; message: string }>(`/crm/customers/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

export async function deleteCustomer(id: string) {
  return apiClient<MutationSuccessResponse>(`/crm/customers/${id}`, {
    method: 'DELETE'
  });
}

export async function getCustomerContacts(id: string): Promise<CustomerContactsResponse> {
  return apiClient<CustomerContactsResponse>(`/crm/customers/${id}/contacts`);
}

export async function createCustomerContact(
  customerId: string,
  data: CustomerContactMutationPayload
) {
  return apiClient<MutationSuccessResponse>(`/crm/customers/${customerId}/contacts`, {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

export async function updateCustomerContact(
  customerId: string,
  contactId: string,
  data: CustomerContactMutationPayload
) {
  return apiClient<MutationSuccessResponse>(`/crm/customers/${customerId}/contacts/${contactId}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

export async function deleteCustomerContact(customerId: string, contactId: string) {
  return apiClient<MutationSuccessResponse>(`/crm/customers/${customerId}/contacts/${contactId}`, {
    method: 'DELETE'
  });
}
