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

/**
 * Maintenance interval configuration. Defines how often a vehicle needs a
 * given service. Identity is (vehicle, maintenanceType, serviceItem) — a
 * vehicle carries several intervals of the same coarse type with different
 * items (oil every 10k km, tires every 50k km, both PREVENTIVE). Uniqueness
 * is enforced by a COALESCE expression index in the migration (nullable
 * service_item), not a TypeORM @Unique.
 */
@Entity({ name: 'maintenance_intervals', schema: 'freight' })
@Index(['vehicleId', 'maintenanceType'])
export class MaintenanceInterval extends BaseEntity {
  @Column({ name: 'vehicle_id', type: 'uuid' })
  vehicleId!: string;

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

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

  /** What is serviced — "oil change", "tires", … Null = generic for the type. */
  @Column({ name: 'service_item', type: 'varchar', length: 120, nullable: true })
  serviceItem?: string | null;

  /** Maintenance interval in kilometers. E.g., 10000 for oil changes every 10k km. */
  @Column({ name: 'interval_km', type: 'numeric', precision: 14, scale: 2, nullable: true })
  intervalKm?: number | null;

  /** Maintenance interval in days. E.g., 365 for annual inspection. */
  @Column({ name: 'interval_days', type: 'integer', nullable: true })
  intervalDays?: number | null;

  /** Human-readable description. E.g., "Oil and filter change". */
  @Column({ name: 'description', type: 'text', nullable: true })
  description?: string | null;

  /** Is this interval active? Can be disabled without deleting historical data. */
  @Column({ name: 'is_active', type: 'boolean', default: true })
  isActive!: boolean;
}
