import { Entity, Column, Index } from 'typeorm';
import { BaseEntity } from '@edr/api-common';

/**
 * Append-only audit log for fleet activity. One row per transition. Queried by
 * `vehicleId` (vehicle timeline) or `driverId` (driver timeline); an event may
 * carry both so a driver↔vehicle assignment or a mile assignment shows on both.
 * `createdAt` (from BaseEntity) is the event time.
 */
export enum FleetEventType {
  DRIVER_REGISTERED = 'DRIVER_REGISTERED',
  VEHICLE_REGISTERED = 'VEHICLE_REGISTERED',
  DRIVER_ASSIGNED = 'DRIVER_ASSIGNED',
  DRIVER_UNASSIGNED = 'DRIVER_UNASSIGNED',
  VEHICLE_STATUS_CHANGED = 'VEHICLE_STATUS_CHANGED',
  VEHICLE_AVAILABILITY_CHANGED = 'VEHICLE_AVAILABILITY_CHANGED',
  MILE_VEHICLE_ASSIGNED = 'MILE_VEHICLE_ASSIGNED',
  MILE_VEHICLE_RELEASED = 'MILE_VEHICLE_RELEASED',
  MILE_STATUS_CHANGED = 'MILE_STATUS_CHANGED',
}

@Entity({ name: 'fleet_events', schema: 'freight' })
export class FleetEvent extends BaseEntity {
  @Column({ name: 'event_type', type: 'varchar' })
  eventType!: FleetEventType;

  @Index()
  @Column({ name: 'vehicle_id', type: 'uuid', nullable: true })
  vehicleId?: string | null;

  @Index()
  @Column({ name: 'driver_id', type: 'uuid', nullable: true })
  driverId?: string | null;

  @Column({ name: 'first_mile_id', type: 'uuid', nullable: true })
  firstMileId?: string | null;

  @Column({ name: 'last_mile_id', type: 'uuid', nullable: true })
  lastMileId?: string | null;

  /** Previous value for a transition (e.g. old status/availability). */
  @Column({ name: 'from_value', type: 'varchar', nullable: true })
  fromValue?: string | null;

  /** New value for a transition (e.g. new status/availability). */
  @Column({ name: 'to_value', type: 'varchar', nullable: true })
  toValue?: string | null;

  /** Human-readable summary token (driver name, plate, booking ref, mile). */
  @Column({ name: 'label', type: 'varchar', nullable: true })
  label?: string | null;

  @Column({ name: 'metadata', type: 'jsonb', nullable: true })
  metadata?: Record<string, unknown> | null;
}
