import { api } from './client';
import type { ApiResponse, PaginatedResult, BaseFilters } from '../../types';

// Customer types (using Fleet as customer for commercial customers)
export interface Customer {
  id: string;
  tenant_id: string;
  name: string;
  code?: string;
  contact_name?: string;
  contact_email?: string;
  contact_phone?: string;
  discount_labor_pct: number;
  discount_parts_pct: number;
  credit_days: number;
  credit_limit: number;
  vehicle_count: number;
  notes?: string;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

export interface CustomerFilters extends BaseFilters {
  isActive?: boolean;
}

export interface CreateCustomerRequest {
  name: string;
  code?: string;
  contact_name?: string;
  contact_email?: string;
  contact_phone?: string;
  discount_labor_pct?: number;
  discount_parts_pct?: number;
  credit_days?: number;
  credit_limit?: number;
  notes?: string;
}

export interface UpdateCustomerRequest extends Partial<CreateCustomerRequest> {
  is_active?: boolean;
}

export const customersApi = {
  list: (filters?: CustomerFilters) => {
    const params = new URLSearchParams();
    if (filters?.isActive !== undefined) params.append('isActive', String(filters.isActive));
    if (filters?.search) params.append('search', filters.search);
    if (filters?.page) params.append('page', String(filters.page));
    if (filters?.pageSize) params.append('limit', String(filters.pageSize));

    return api.get<ApiResponse<PaginatedResult<Customer>>>(`/fleets?${params.toString()}`);
  },

  getById: (id: string) =>
    api.get<ApiResponse<Customer>>(`/fleets/${id}`),

  create: (data: CreateCustomerRequest) =>
    api.post<ApiResponse<Customer>>('/fleets', data),

  update: (id: string, data: UpdateCustomerRequest) =>
    api.patch<ApiResponse<Customer>>(`/fleets/${id}`, data),

  delete: (id: string) =>
    api.delete<ApiResponse<null>>(`/fleets/${id}`),

  // Get vehicles for a customer
  getVehicles: (customerId: string) =>
    api.get<ApiResponse<{ data: unknown[] }>>(`/vehicles?customerId=${customerId}`),
};
