import { BaseEntity } from '@edr/api-common';
import { Entity, Column, ManyToOne, JoinColumn, Index } from 'typeorm';
import { Vehicle } from '../../vehicles/entities/vehicle.entity';

export enum MaintenanceType {
  PREVENTIVE = 'PREVENTIVE',
  CORRECTIVE = 'CORRECTIVE',
  INSPECTION = 'INSPECTION',
  REPAIR = 'REPAIR',
}

export enum MaintenanceStatus {
  SCHEDULED = 'SCHEDULED',
  IN_PROGRESS = 'IN_PROGRESS',
  COMPLETED = 'COMPLETED',
  CANCELLED = 'CANCELLED',
  OVERDUE = 'OVERDUE',
}

@Entity({ name: 'maintenance_schedules', schema: 'freight' })
@Index(['vehicleId', 'scheduledDate'])
export class MaintenanceSchedule extends BaseEntity {
  @Column({ name: 'vehicle_id', type: 'uuid' })
  vehicleId!: string;

  @ManyToOne(() => Vehicle, { eager: false })
  @JoinColumn({ name: 'vehicle_id' })
  vehicle!: Vehicle;

  @Column({ name: 'maintenance_type', type: 'varchar' })
  maintenanceType!: MaintenanceType;

  /** What is serviced — matches the interval's service_item for auto-scheduling. */
  @Column({ name: 'service_item', type: 'varchar', length: 120, nullable: true })
  serviceItem?: string | null;

  @Column({ name: 'description' })
  description!: string;

  @Column({ name: 'scheduled_date', type: 'timestamptz' })
  scheduledDate!: Date;

  @Column({ name: 'completed_date', type: 'timestamptz', nullable: true })
  completedDate?: Date;

  @Column({ name: 'estimated_cost', type: 'numeric', precision: 14, scale: 2, nullable: true })
  estimatedCost?: number;

  @Column({ name: 'actual_cost', type: 'numeric', precision: 14, scale: 2, nullable: true })
  actualCost?: number;

  @Column({ name: 'status', type: 'varchar', default: MaintenanceStatus.SCHEDULED })
  status!: MaintenanceStatus;

  @Column({ name: 'odometer_reading', type: 'numeric', nullable: true })
  odometerReading?: number;

  @Column({ name: 'service_provider', nullable: true })
  serviceProvider?: string;

  @Column({ name: 'notes', type: 'text', nullable: true })
  notes?: string;

  @Column({ name: 'next_due_km', type: 'numeric', nullable: true })
  nextDueKm?: number;

  @Column({ name: 'next_due_date', type: 'timestamptz', nullable: true })
  nextDueDate?: Date;

  /** Stamped once the km/date-due alert has fired, so the daily check doesn't repeat it. */
  @Column({ name: 'due_notified_at', type: 'timestamptz', nullable: true })
  dueNotifiedAt?: Date;
}
