import { api as apiClient } from '../auth/http';

export type ComplianceType =
  | 'INSPECTION'
  | 'INSURANCE'
  | 'ROADWORTHINESS'
  | 'PERMIT'
  | 'TAX';

export type ComplianceStatus = 'VALID' | 'EXPIRING' | 'EXPIRED';

export type AlertSeverity = 'OVERDUE' | 'DUE_SOON';

export interface ComplianceRecord {
  id: string;
  vehicleId: string;
  vehicle?: {
    id: string;
    plateNumber?: string | null;
    manufacturer?: string | null;
    model?: string | null;
  };
  type: ComplianceType;
  documentNumber?: string | null;
  issuedDate?: string | null;
  expiryDate: string;
  status: ComplianceStatus;
  notes?: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface ComplianceAlert {
  vehicleId: string;
  vehiclePlate?: string;
  kind: string;
  label: string;
  expiryDate: string;
  daysUntil: number;
  severity: AlertSeverity;
}

export interface ComplianceListFilters {
  vehicleId?: string;
  type?: ComplianceType;
}

export interface SaveCompliancePayload {
  vehicleId: string;
  type: ComplianceType;
  documentNumber?: string;
  issuedDate?: string;
  expiryDate: string;
  status?: ComplianceStatus;
  notes?: string;
}

export const complianceService = {
  list: (filters: ComplianceListFilters = {}) => {
    const params = new URLSearchParams();
    if (filters.vehicleId) params.set('vehicleId', filters.vehicleId);
    if (filters.type) params.set('type', filters.type);
    const qs = params.toString();
    return apiClient.get<ComplianceRecord[]>(`/compliance${qs ? `?${qs}` : ''}`);
  },
  getAlerts: () => apiClient.get<ComplianceAlert[]>('/compliance/alerts'),
  getById: (id: string) => apiClient.get<ComplianceRecord>(`/compliance/${id}`),
  create: (data: SaveCompliancePayload) =>
    apiClient.post<ComplianceRecord>('/compliance', data),
  update: (id: string, data: Partial<SaveCompliancePayload>) =>
    apiClient.patch<ComplianceRecord>(`/compliance/${id}`, data),
  remove: (id: string) => apiClient.delete(`/compliance/${id}`),
};
