import { api } from '@/auth/http';

export type IncidentType = 'ACCIDENT' | 'BREAKDOWN' | 'TRAFFIC_VIOLATION' | 'THEFT' | 'OTHER';
export type IncidentSeverity = 'MINOR' | 'MODERATE' | 'MAJOR' | 'CRITICAL';
export type IncidentStatus =
  | 'REPORTED'
  | 'UNDER_REVIEW'
  | 'CLAIM_FILED'
  | 'RESOLVED'
  | 'CLOSED';

export interface Incident {
  id: string;
  vehicleId?: string | null;
  driverId?: string | null;
  bookingId?: string | null;
  type: IncidentType;
  severity: IncidentSeverity;
  occurredAt: string;
  location?: string | null;
  description: string;
  /** API sends numeric as string; coerce with Number. */
  damageEstimate?: number | string | null;
  status: IncidentStatus;
  insuranceClaimNumber?: string | null;
  reportedBy?: string | null;
  vehicle?: {
    id: string;
    plateNumber?: string | null;
    registrationNumber?: string | null;
  } | null;
  driver?: {
    id: string;
    firstName?: string | null;
    lastName?: string | null;
  } | null;
  createdAt: string;
  updatedAt: string;
}

export interface IncidentFilters {
  vehicleId?: string;
  driverId?: string;
  status?: IncidentStatus;
  type?: IncidentType;
}

export interface DriverIncidentStats {
  total: number;
  byType: Record<string, number>;
  lastIncidentAt: string | null;
}

export interface SaveIncidentPayload {
  vehicleId?: string;
  driverId?: string;
  bookingId?: string;
  type: IncidentType;
  severity: IncidentSeverity;
  occurredAt: string;
  location?: string;
  description: string;
  damageEstimate?: number;
  status?: IncidentStatus;
  insuranceClaimNumber?: string;
  reportedBy?: string;
}

export const incidentsService = {
  getAll: (filters: IncidentFilters = {}) => {
    const params = new URLSearchParams();
    if (filters.vehicleId) params.set('vehicleId', filters.vehicleId);
    if (filters.driverId) params.set('driverId', filters.driverId);
    if (filters.status) params.set('status', filters.status);
    if (filters.type) params.set('type', filters.type);
    const qs = params.toString();
    return api.get<Incident[]>(`/incidents${qs ? `?${qs}` : ''}`);
  },
  getByDriver: (driverId: string) => api.get<Incident[]>(`/incidents/driver/${driverId}`),
  getDriverStats: (driverId: string) =>
    api.get<DriverIncidentStats>(`/incidents/driver/${driverId}/stats`),
  getById: (id: string) => api.get<Incident>(`/incidents/${id}`),
  create: (data: SaveIncidentPayload) => api.post<Incident>('/incidents', data),
  update: (id: string, data: Partial<SaveIncidentPayload>) =>
    api.patch<Incident>(`/incidents/${id}`, data),
  delete: (id: string) => api.delete(`/incidents/${id}`),
};
