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

export enum AcquisitionType {
  PURCHASE = 'PURCHASE',
  LEASE = 'LEASE',
  RENTAL = 'RENTAL',
}

export enum AcquisitionStatus {
  ACTIVE = 'ACTIVE',
  LEASE_EXPIRING = 'LEASE_EXPIRING',
  DISPOSED = 'DISPOSED',
}

@Entity({ name: 'asset_acquisitions', schema: 'freight' })
@Index(['vehicleId', 'acquisitionDate'])
export class AssetAcquisition extends BaseEntity {
  /** WHAT was acquired (vehicle, parts, equipment…) — the asset itself. */
  @Column({ name: 'item_name', type: 'varchar', length: 200, nullable: true })
  itemName?: string;

  /** Optional link — only when the acquisition IS a fleet vehicle. Parts and
   *  general procurement stay unlinked so reports don't misattribute them. */
  @Column({ name: 'vehicle_id', type: 'uuid', nullable: true })
  vehicleId?: string;

  @ManyToOne(() => Vehicle, { eager: false, nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'vehicle_id' })
  vehicle?: Vehicle;

  @Column({ name: 'vendor_id', type: 'uuid', nullable: true })
  vendorId?: string;

  @ManyToOne(() => Vendor, { eager: false, nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'vendor_id' })
  vendor?: Vendor;

  @Column({ name: 'acquisition_type', type: 'varchar' })
  acquisitionType!: AcquisitionType;

  @Column({ name: 'acquisition_date', type: 'date' })
  acquisitionDate!: string;

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

  @Column({ name: 'useful_life_months', type: 'int', nullable: true })
  usefulLifeMonths?: number;

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

  @Column({ name: 'lease_start', type: 'date', nullable: true })
  leaseStart?: string;

  @Column({ name: 'lease_end', type: 'date', nullable: true })
  leaseEnd?: string;

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

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

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