import { api as apiClient } from '../auth/http';
import { URL_CONSTANTS } from '@/constants/URLS';

export type DriverStatus = 'ACTIVE' | 'INACTIVE' | 'SUSPENDED' | 'ON_LEAVE';

export interface DriverListFilters {
  status?: DriverStatus;
  search?: string;
  page?: number;
  limit?: number;
  sortBy?: string;
  sortOrder?: 'ASC' | 'DESC';
}

export interface Driver {
  id: string;
  licenseNumber: string;
  firstName: string;
  lastName: string;
  email: string;
  phoneNumber: string;
  dateOfBirth: string;
  licenseExpiryDate: string;
  status: DriverStatus;
  vehicleTypesAuthorized: string[];
  address?: string | null;
  emergencyContact?: string | null;
  notes?: string | null;
  totalTrips: number;
  rating: number;
  createdAt: string;
  updatedAt: string;
}

export type SaveDriverPayload = Omit<
  Driver,
  'id' | 'createdAt' | 'updatedAt' | 'totalTrips' | 'rating'
>;

export const driversService = {
  getAll: (filters: DriverListFilters = {}) => {
    const params = new URLSearchParams();
    if (filters.status) params.set('status', filters.status);
    if (filters.search) params.set('search', filters.search);
    if (filters.page) params.set('page', filters.page.toString());
    if (filters.limit) params.set('limit', filters.limit.toString());
    if (filters.sortBy) params.set('sortBy', filters.sortBy);
    if (filters.sortOrder) params.set('sortOrder', filters.sortOrder);
    const qs = params.toString();
    return apiClient.get<Driver[]>(
      `${URL_CONSTANTS.DRIVERS.BASE}${qs ? `?${qs}` : ''}`,
    );
  },
  getById: (id: string) => apiClient.get<Driver>(URL_CONSTANTS.DRIVERS.BY_ID(id)),
  create: (data: Partial<SaveDriverPayload>) =>
    apiClient.post(URL_CONSTANTS.DRIVERS.BASE, data),
  update: (id: string, data: Partial<SaveDriverPayload>) =>
    apiClient.patch(URL_CONSTANTS.DRIVERS.BY_ID(id), data),
  delete: (id: string) => apiClient.delete(URL_CONSTANTS.DRIVERS.BY_ID(id)),
};
