import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { FleetEvent, FleetEventType } from './entities/fleet-event.entity';

export interface FleetEventInput {
  eventType: FleetEventType;
  vehicleId?: string | null;
  driverId?: string | null;
  firstMileId?: string | null;
  lastMileId?: string | null;
  fromValue?: string | null;
  toValue?: string | null;
  label?: string | null;
  metadata?: Record<string, unknown> | null;
}

@Injectable()
export class FleetHistoryService {
  private readonly logger = new Logger(FleetHistoryService.name);

  constructor(
    @InjectRepository(FleetEvent)
    private readonly eventRepo: Repository<FleetEvent>,
  ) {}

  /**
   * Append an audit event. Best-effort: recording history must never break the
   * business operation that triggered it, so failures are logged and swallowed.
   */
  async record(input: FleetEventInput): Promise<void> {
    try {
      await this.eventRepo.save(this.eventRepo.create(input));
    } catch (err) {
      this.logger.error(
        `Failed to record fleet event ${input.eventType}: ${String(err)}`,
      );
    }
  }

  getVehicleHistory(vehicleId: string): Promise<FleetEvent[]> {
    return this.eventRepo.find({
      where: { vehicleId },
      order: { createdAt: 'DESC' },
    });
  }

  getDriverHistory(driverId: string): Promise<FleetEvent[]> {
    return this.eventRepo.find({
      where: { driverId },
      order: { createdAt: 'DESC' },
    });
  }
}
