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;
  faydaVerified?: boolean;
  faydaSub?: string | null;
  totalTrips: number;
  rating: number;
  createdAt: string;
  updatedAt: string;
}

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

/** A stored driver document (code "driver_docs"). */
export interface DriverDocument {
  id: string;
  name: string;
  url: string;
  size: number;
  mimeType: string;
  code: string;
  createdAt: string;
}

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)),

  // ── Driver documents (upload area code "driver_docs") ──
  listDocuments: (id: string) =>
    apiClient.get<DriverDocument[]>(`${URL_CONSTANTS.DRIVERS.BY_ID(id)}/documents`),
  uploadDocuments: (id: string, files: File[]) => {
    const form = new FormData();
    for (const f of files) form.append('files', f);
    return apiClient.post<DriverDocument[]>(
      `${URL_CONSTANTS.DRIVERS.BY_ID(id)}/documents`,
      form,
    );
  },
  removeDocument: (id: string, fileId: string) =>
    apiClient.delete(`${URL_CONSTANTS.DRIVERS.BY_ID(id)}/documents/${fileId}`),
};
