/**
 * @ai-summary Hook for batch-creating maintenance schedules from manual extraction results
 * @ai-context Maps extracted MaintenanceScheduleItem[] to CreateScheduleRequest[] and creates via API
 */

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { maintenanceApi } from '../api/maintenance.api';
import type { CreateScheduleRequest, MaintenanceScheduleResponse } from '../types/maintenance.types';
import type { MaintenanceScheduleItem } from '../../documents/hooks/useManualExtraction';

interface CreateSchedulesParams {
  vehicleId: string;
  items: MaintenanceScheduleItem[];
}

export function useCreateSchedulesFromExtraction() {
  const queryClient = useQueryClient();

  return useMutation<MaintenanceScheduleResponse[], Error, CreateSchedulesParams>({
    mutationFn: async ({ vehicleId, items }) => {
      const results: MaintenanceScheduleResponse[] = [];
      for (const item of items) {
        if (item.subtypes.length === 0) continue;
        if (item.intervalMiles === null && item.intervalMonths === null) continue;
        const request: CreateScheduleRequest = {
          vehicleId,
          category: 'routine_maintenance',
          subtypes: item.subtypes,
          scheduleType: 'interval',
          intervalMiles: item.intervalMiles ?? undefined,
          intervalMonths: item.intervalMonths ?? undefined,
        };
        const created = await maintenanceApi.createSchedule(request);
        results.push(created);
      }
      return results;
    },
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ['maintenanceSchedules', variables.vehicleId] });
      queryClient.invalidateQueries({ queryKey: ['maintenanceUpcoming', variables.vehicleId] });
    },
  });
}
