import { Entity, Column, Index, ManyToOne, OneToMany, JoinColumn } from 'typeorm';
import { BookingSpecialItemSupplierEntity } from './booking-special-item-supplier.entity';
import { BaseEntity } from '../database/base.entity';
import { BookingEntity } from './booking.entity';
import { SupplierEntity } from './supplier.entity';

@Entity('booking_special_items')
@Index('ix_booking_special_items_tenant_booking', ['tenant_id', 'booking_id'], {
  where: '"is_deleted" = false',
})
export class BookingSpecialItemEntity extends BaseEntity {
  @ManyToOne(() => BookingEntity, (b) => b.special_items, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'booking_id' })
  booking: BookingEntity;

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

  @Column({ type: 'varchar', length: 255 })
  service_name: string;

  @Column({ type: 'decimal', precision: 12, scale: 2 })
  total_price: number;

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

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

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

  // ── Tax snapshot (added 2026-05-07 — see migration 1777700000000) ────
  // Re-snapshotted at booking-create from quote (Q1=C); immutable
  // on edit unless refresh_tax: true (Q2=B).
  @Column({ type: 'jsonb', nullable: true })
  tax_breakdown: Record<string, Record<string, number>> | null;

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

  // ── Supplier assignment + cost (parallel to transport/activity) ─────
  // Special items are ad-hoc with no pricing master, so
  // actual_supplier_cost is NEVER snapshotted at booking-create —
  // ops fills it manually.
  @ManyToOne(() => SupplierEntity, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'supplier_id' })
  supplier: SupplierEntity | null;

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

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

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

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

  /** Per-line customer-side slab snapshot (added in migration
   *  1781100000000). See query-quote-hotel.entity.ts for the policy. */
  @Column({ type: 'jsonb', nullable: true })
  tax_snapshot: Record<string, unknown> | null;

  /** Multi-supplier junction rows — see migration 1784000. */
  @OneToMany(
    () => BookingSpecialItemSupplierEntity,
    (s) => s.special_item,
  )
  suppliers: BookingSpecialItemSupplierEntity[];
}
