/**
 * Booking ORM Entity (Infrastructure Layer)
 *
 * TypeORM entity for booking persistence
 */

import {
  Entity,
  Column,
  PrimaryColumn,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  OneToMany,
  JoinColumn,
} from 'typeorm';
import { UserOrmEntity } from './user.orm-entity';
import { OrganizationOrmEntity } from './organization.orm-entity';
import { ContainerOrmEntity } from './container.orm-entity';

/**
 * Address stored as JSON
 */
export interface AddressJson {
  street: string;
  city: string;
  postalCode: string;
  country: string;
}

/**
 * Party (shipper/consignee) stored as JSON
 */
export interface PartyJson {
  name: string;
  address: AddressJson;
  contactName: string;
  contactEmail: string;
  contactPhone: string;
}

@Entity('bookings')
@Index('idx_bookings_booking_number', ['bookingNumber'], { unique: true })
@Index('idx_bookings_user', ['userId'])
@Index('idx_bookings_organization', ['organizationId'])
@Index('idx_bookings_rate_quote', ['rateQuoteId'])
@Index('idx_bookings_status', ['status'])
@Index('idx_bookings_created_at', ['createdAt'])
export class BookingOrmEntity {
  @PrimaryColumn('uuid')
  id: string;

  @Column({ name: 'booking_number', type: 'varchar', length: 20, unique: true })
  bookingNumber: string;

  @Column({ name: 'user_id', type: 'uuid' })
  userId: string;

  @ManyToOne(() => UserOrmEntity, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'user_id' })
  user: UserOrmEntity;

  @Column({ name: 'organization_id', type: 'uuid' })
  organizationId: string;

  @ManyToOne(() => OrganizationOrmEntity, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'organization_id' })
  organization: OrganizationOrmEntity;

  @Column({ name: 'rate_quote_id', type: 'uuid' })
  rateQuoteId: string;

  @Column({ type: 'varchar', length: 50 })
  status: string;

  @Column({ type: 'jsonb' })
  shipper: PartyJson;

  @Column({ type: 'jsonb' })
  consignee: PartyJson;

  @Column({ name: 'cargo_description', type: 'text' })
  cargoDescription: string;

  @OneToMany(() => ContainerOrmEntity, container => container.booking, {
    cascade: true,
    eager: true,
  })
  containers: ContainerOrmEntity[];

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

  @Column({ name: 'commission_rate', type: 'decimal', precision: 5, scale: 2, nullable: true })
  commissionRate: number | null;

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

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date;
}
