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

import { Booking } from '../../bookings/entities/booking.entity';
import { Vehicle } from '../../vehicles/entities/vehicle.entity';

export const LAST_MILE_STATUSES = [
  'PAYMENT_PENDING',
  'READY_TO_TRANSIT',
  'IN_TRANSIT',
  'DELIVERED',
] as const;

export type LastMileStatus = (typeof LAST_MILE_STATUSES)[number];

@Entity({ name: 'last_mile', schema: 'freight' })
@Index(['bookingId'])
@Index(['status'])
@Index(['vehicleId'])
export class LastMile extends BaseEntity {
  @Column({ name: 'booking_id', type: 'uuid' })
  bookingId!: string;

  @ManyToOne(() => Booking, { nullable: false, eager: false })
  @JoinColumn({ name: 'booking_id' })
  booking?: Booking;

  @Column({ name: 'status', type: 'varchar', length: 30, default: 'PAYMENT_PENDING' })
  status!: LastMileStatus;

  @Column({ name: 'advanced_payment', type: 'numeric', precision: 14, scale: 2, default: 0 })
  advancedPayment!: number;

  @Column({ name: 'remaining_payment', type: 'numeric', precision: 14, scale: 2, default: 0 })
  remainingPayment!: number;

  @Column({ name: 'estimated_km', type: 'numeric', precision: 10, scale: 2, nullable: true })
  estimatedKm?: number | null;

  @Column({ name: 'exact_km', type: 'numeric', precision: 10, scale: 2, nullable: true })
  exactKm?: number | null;

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

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