/**
 * @ai-summary Type definitions for maintenance feature
 * @ai-context Supports three categories with specific subtypes, multiple selections allowed
 */

import { z } from 'zod';

// Category types
export type MaintenanceCategory = 'routine_maintenance' | 'repair' | 'performance_upgrade';
export type ScheduleType = 'interval' | 'fixed_date' | 'time_since_last';

// Subtype definitions (constants for validation)
export const ROUTINE_MAINTENANCE_SUBTYPES = [
  'Accelerator Pedal',
  'Air Filter Element',
  'Brakes and Traction Control',
  'Cabin Air Filter / Purifier',
  'Coolant',
  'Doors',
  'Drive Belt',
  'Engine Oil',
  'Evaporative Emissions System',
  'Exhaust System',
  'Fluid - A/T',
  'Fluid - Differential',
  'Fluid - M/T',
  'Fluid Filter - A/T',
  'Fluids',
  'Fuel Delivery and Air Induction',
  'Hood Shock / Support',
  'Neutral Safety Switch',
  'Parking Brake System',
  'Restraints and Safety Systems',
  'Shift Interlock, A/T',
  'Spark Plug',
  'Steering and Suspension',
  'Tires',
  'Trunk / Liftgate Shock / Support',
  'Washer Fluid',
  'Wiper Blade'
] as const;

export const REPAIR_SUBTYPES = [
  'Engine',
  'Transmission',
  'Drivetrain',
  'Exterior',
  'Interior'
] as const;

export const PERFORMANCE_UPGRADE_SUBTYPES = [
  'Engine',
  'Drivetrain',
  'Suspension',
  'Wheels/Tires',
  'Exterior'
] as const;

// Database record types (camelCase for TypeScript)
export interface MaintenanceRecord {
  id: string;
  userId: string;
  vehicleId: string;
  category: MaintenanceCategory;
  subtypes: string[];
  date: string;
  odometerReading?: number;
  cost?: number;
  shopName?: string;
  notes?: string;
  createdAt: string;
  updatedAt: string;
}

export interface MaintenanceSchedule {
  id: string;
  userId: string;
  vehicleId: string;
  category: MaintenanceCategory;
  subtypes: string[];
  intervalMonths?: number;
  intervalMiles?: number;
  lastServiceDate?: string;
  lastServiceMileage?: number;
  nextDueDate?: string;
  nextDueMileage?: number;
  isActive: boolean;
  emailNotifications: boolean;
  scheduleType: ScheduleType;
  fixedDueDate?: string | null;
  reminderDays1?: number | null;
  reminderDays2?: number | null;
  reminderDays3?: number | null;
  createdAt: string;
  updatedAt: string;
}

// Zod schemas for validation (camelCase for API)
export const MaintenanceCategorySchema = z.enum(['routine_maintenance', 'repair', 'performance_upgrade']);
export const ScheduleTypeSchema = z.enum(['interval', 'fixed_date', 'time_since_last']);

const reminderDaysValidator = z.number().int().positive().refine(
  (val) => [1, 7, 14, 30, 60].includes(val),
  { message: 'Reminder days must be one of: 1, 7, 14, 30, 60' }
);

export const CreateMaintenanceRecordSchema = z.object({
  vehicleId: z.string().uuid(),
  category: MaintenanceCategorySchema,
  subtypes: z.array(z.string()).min(1),
  date: z.string(),
  odometerReading: z.number().int().positive().optional(),
  cost: z.number().positive().optional(),
  shopName: z.string().max(200).optional(),
  notes: z.string().max(10000).optional(),
});
export type CreateMaintenanceRecordRequest = z.infer<typeof CreateMaintenanceRecordSchema>;

export const UpdateMaintenanceRecordSchema = z.object({
  category: MaintenanceCategorySchema.optional(),
  subtypes: z.array(z.string()).min(1).optional(),
  date: z.string().optional(),
  odometerReading: z.number().int().positive().nullable().optional(),
  cost: z.number().positive().nullable().optional(),
  shopName: z.string().max(200).nullable().optional(),
  notes: z.string().max(10000).nullable().optional(),
});
export type UpdateMaintenanceRecordRequest = z.infer<typeof UpdateMaintenanceRecordSchema>;

export const CreateScheduleSchema = z.object({
  vehicleId: z.string().uuid(),
  category: MaintenanceCategorySchema,
  subtypes: z.array(z.string()).min(1),
  intervalMonths: z.number().int().positive().optional(),
  intervalMiles: z.number().int().positive().optional(),
  emailNotifications: z.boolean().optional(),
  scheduleType: ScheduleTypeSchema.optional().default('interval'),
  fixedDueDate: z.string().optional(),
  reminderDays1: reminderDaysValidator.optional(),
  reminderDays2: reminderDaysValidator.optional(),
  reminderDays3: reminderDaysValidator.optional(),
});
export type CreateScheduleRequest = z.infer<typeof CreateScheduleSchema>;

export const UpdateScheduleSchema = z.object({
  category: MaintenanceCategorySchema.optional(),
  subtypes: z.array(z.string()).min(1).optional(),
  intervalMonths: z.number().int().positive().nullable().optional(),
  intervalMiles: z.number().int().positive().nullable().optional(),
  isActive: z.boolean().optional(),
  emailNotifications: z.boolean().optional(),
  scheduleType: ScheduleTypeSchema.optional(),
  fixedDueDate: z.string().nullable().optional(),
  reminderDays1: reminderDaysValidator.nullable().optional(),
  reminderDays2: reminderDaysValidator.nullable().optional(),
  reminderDays3: reminderDaysValidator.nullable().optional(),
});
export type UpdateScheduleRequest = z.infer<typeof UpdateScheduleSchema>;

// Response types
export interface MaintenanceRecordResponse extends MaintenanceRecord {
  subtypeCount: number;
}

// TCO aggregation stats
export interface MaintenanceCostStats {
  totalCost: number;
  recordCount: number;
}

export interface MaintenanceScheduleResponse extends MaintenanceSchedule {
  subtypeCount: number;
  isDueSoon?: boolean;
  isOverdue?: boolean;
}

// Validation helpers
export function getSubtypesForCategory(category: MaintenanceCategory): readonly string[] {
  switch (category) {
    case 'routine_maintenance': return ROUTINE_MAINTENANCE_SUBTYPES;
    case 'repair': return REPAIR_SUBTYPES;
    case 'performance_upgrade': return PERFORMANCE_UPGRADE_SUBTYPES;
  }
}

export function validateSubtypes(category: MaintenanceCategory, subtypes: string[]): boolean {
  if (!subtypes || subtypes.length === 0) return false;
  const validSubtypes = getSubtypesForCategory(category);
  return subtypes.every(st => validSubtypes.includes(st as any));
}

export function getCategoryDisplayName(category: MaintenanceCategory): string {
  switch (category) {
    case 'routine_maintenance': return 'Routine Maintenance';
    case 'repair': return 'Repair';
    case 'performance_upgrade': return 'Performance Upgrade';
  }
}
