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

// Diagnostic Result type
export type DiagnosticResult = 'pass' | 'fail' | 'needs_attention';

// Types
export interface Diagnostic {
  id: string;
  tenant_id: string;
  order_id: string | null;
  order_number: string | null;
  vehicle_id: string;
  vehicle_info: string;
  customer_name: string;
  diagnostic_type: DiagnosticType;
  equipment: string | null;
  performed_at: string;
  performed_by: string | null;
  technician_name: string | null;
  result: DiagnosticResult | null;
  summary: string | null;
  raw_data: Record<string, unknown> | null;
  created_at: string;
  updated_at: string | null;
}

export interface DiagnosticItem {
  id: string;
  diagnostic_id: string;
  component: string;
  test_name: string;
  value: string;
  unit: string | null;
  min_value: number | null;
  max_value: number | null;
  result: DiagnosticResult;
  notes: string | null;
}

export interface CreateDiagnosticRequest {
  vehicle_id: string;
  order_id?: string;
  diagnostic_type: DiagnosticType;
  equipment?: string;
  performed_by?: string;
  summary?: string;
}

export interface DiagnosticFilters extends BaseFilters {
  diagnostic_type?: DiagnosticType;
  vehicle_id?: string;
  order_id?: string;
  result?: DiagnosticResult;
}

// API
export const diagnosticsApi = {
  // List diagnostics with filters
  list: (filters?: DiagnosticFilters) =>
    api.get<ApiResponse<PaginatedResult<Diagnostic>>>('/diagnostics', {
      params: filters,
    }),

  // Get single diagnostic
  getById: (id: string) =>
    api.get<ApiResponse<Diagnostic>>(`/diagnostics/${id}`),

  // Create new diagnostic
  create: (data: CreateDiagnosticRequest) =>
    api.post<ApiResponse<Diagnostic>>('/diagnostics', data),

  // Update diagnostic
  update: (id: string, data: Partial<Diagnostic>) =>
    api.patch<ApiResponse<Diagnostic>>(`/diagnostics/${id}`, data),

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

  // Get diagnostic items
  getItems: (diagnosticId: string) =>
    api.get<ApiResponse<DiagnosticItem[]>>(`/diagnostics/${diagnosticId}/items`),

  // Add item to diagnostic
  addItem: (diagnosticId: string, item: Partial<DiagnosticItem>) =>
    api.post<ApiResponse<DiagnosticItem>>(`/diagnostics/${diagnosticId}/items`, item),

  // Update result
  setResult: (id: string, result: DiagnosticResult, summary?: string) =>
    api.patch<ApiResponse<Diagnostic>>(`/diagnostics/${id}`, { result, summary }),

  // Get diagnostics by vehicle
  getByVehicle: (vehicleId: string) =>
    api.get<ApiResponse<Diagnostic[]>>(`/vehicles/${vehicleId}/diagnostics`),

  // Get diagnostics by order
  getByOrder: (orderId: string) =>
    api.get<ApiResponse<Diagnostic[]>>(`/service-orders/${orderId}/diagnostics`),
};
