import { Entity, Column, ManyToOne, JoinColumn, Index } from 'typeorm';
import { BaseEntity } from '../database/base.entity';
import { BookingTransportItemEntity } from './booking-transport-item.entity';
import { SupplierEntity } from './supplier.entity';
import { DriverEntity } from './driver.entity';

/**
 * One row per (transport_item, supplier) assignment. Junction table
 * that replaces the fixed `supplier_id` + `supplier_2_id` columns on
 * booking_transport_items — see migration 1784000 for the rationale
 * and 5-phase cutover plan.
 *
 * `role` is a short controlled vocab ("primary" / "secondary" today;
 * "driver", "guide", "car" once ops asks). Kept as varchar so new
 * roles don't need an enum migration.
 *
 * `actual_supplier_cost` moves off the item onto here so each supplier
 * carries its own billing rate — settlement sums the column instead
 * of dividing a single item-level number.
 */
@Entity('booking_transport_item_suppliers')
@Index(['tenant_id', 'transport_item_id'])
@Index(['tenant_id', 'supplier_id'])
export class BookingTransportItemSupplierEntity extends BaseEntity {
  @ManyToOne(() => BookingTransportItemEntity, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'transport_item_id' })
  transport_item: BookingTransportItemEntity;

  @Column({ type: 'uuid' })
  transport_item_id: string;

  @ManyToOne(() => SupplierEntity, { nullable: true })
  @JoinColumn({ name: 'supplier_id' })
  supplier: SupplierEntity | null;

  @Column({ type: 'uuid', nullable: true })
  supplier_id: string | null;

  /** Free-text fallback when master creation fails at assign time.
   *  Auto-promotion still runs on the FE — this column exists as the
   *  safety net, not the primary path. */
  @Column({ type: 'varchar', length: 255, nullable: true })
  supplier_name_text: string | null;

  @Column({ type: 'varchar', length: 50, nullable: true })
  supplier_phone_text: string | null;

  @Column({ type: 'varchar', length: 30, default: 'primary' })
  role: string;

  @Column({ type: 'int', default: 0 })
  sort_order: number;

  @Column({ type: 'decimal', precision: 12, scale: 2, nullable: true })
  actual_supplier_cost: number | null;

  @ManyToOne(() => DriverEntity, { nullable: true })
  @JoinColumn({ name: 'driver_id' })
  driver: DriverEntity | null;

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

  @Column({ type: 'varchar', length: 255, nullable: true })
  driver_name_text: string | null;

  @Column({ type: 'varchar', length: 50, nullable: true })
  driver_phone_text: string | null;
}
