/**
 * @ai-summary Input validation for fuel logs API
 */

import { z } from 'zod';
import { FuelType } from '../domain/fuel-logs.types';

// Enhanced create schema (Phase 3)
export const createFuelLogSchema = z.object({
  vehicleId: z.string().uuid(),
  dateTime: z.string().datetime(),
  // Distance (one required)
  odometerReading: z.number().int().positive().optional(),
  tripDistance: z.number().positive().optional(),
  // Fuel system
  fuelType: z.nativeEnum(FuelType),
  fuelGrade: z.string().nullable().optional(),
  fuelUnits: z.number().positive(),
  costPerUnit: z.number().positive(),
  // Location (optional)
  locationData: z.object({
    address: z.string().optional(),
    coordinates: z.object({ latitude: z.number(), longitude: z.number() }).optional(),
    googlePlaceId: z.string().optional(),
    stationName: z.string().optional()
  }).optional(),
  notes: z.string().max(1000).optional(),
}).refine((data) => (data.odometerReading && data.odometerReading > 0) || (data.tripDistance && data.tripDistance > 0), {
  message: 'Either odometer reading or trip distance is required',
  path: ['odometerReading']
}).refine((data) => !(data.odometerReading && data.tripDistance), {
  message: 'Cannot specify both odometer reading and trip distance',
  path: ['odometerReading']
});

export const updateFuelLogSchema = z.object({
  dateTime: z.string().datetime().optional(),
  odometerReading: z.number().int().positive().optional(),
  tripDistance: z.number().positive().optional(),
  fuelType: z.nativeEnum(FuelType).optional(),
  fuelGrade: z.string().nullable().optional(),
  fuelUnits: z.number().positive().optional(),
  costPerUnit: z.number().positive().optional(),
  locationData: z.object({
    address: z.string().optional(),
    coordinates: z.object({ latitude: z.number(), longitude: z.number() }).optional(),
    googlePlaceId: z.string().optional(),
    stationName: z.string().optional()
  }).optional(),
  notes: z.string().max(1000).optional(),
}).refine(data => Object.keys(data).length > 0, { message: 'At least one field must be provided for update' });

export function validateCreateFuelLog(data: unknown) {
  return createFuelLogSchema.safeParse(data);
}

export function validateUpdateFuelLog(data: unknown) {
  return updateFuelLogSchema.safeParse(data);
}
