import { Check, Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';
import { BaseEntity } from '../database/base.entity';
import { BookingEntity } from './booking.entity';
import { CurrencyEntity } from './currency.entity';
import { DriverEntity } from './driver.entity';
import { SupplierEntity } from './supplier.entity';

export type MdCashCollectedByType = 'OWN' | 'SUPPLIER';
export type MdCashCollectionRowStatus = 'PENDING' | 'COLLECTED';

/**
 * One Cash collection for MD stamp. Additional Cost stays on
 * booking_cash_collections. Several rows may exist for one booking.
 */
@Entity('md_cash_collections')
@Index('ix_md_cash_tenant_booking', ['tenant_id', 'booking_id'], {
  where: '"is_deleted" = false',
})
@Check('chk_md_cash_status', `"status" IN ('PENDING','COLLECTED')`)
@Check('chk_md_cash_amount_positive', `"amount" > 0`)
@Check(
  'chk_md_cash_collected_by',
  `(
    (
      "collected_by_type" = 'OWN'
      AND "collector_name" IS NOT NULL
      AND "supplier_id" IS NULL
      AND "driver_id" IS NULL
    )
    OR (
      "collected_by_type" = 'SUPPLIER'
      AND "collector_name" IS NULL
      AND "supplier_id" IS NOT NULL
      AND "driver_id" IS NOT NULL
    )
  )`,
)
export class MdCashCollectionEntity extends BaseEntity {
  @ManyToOne(() => BookingEntity, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'booking_id' })
  booking: BookingEntity;

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

  @ManyToOne(() => CurrencyEntity)
  @JoinColumn({ name: 'currency_id' })
  currency: CurrencyEntity;

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

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

  @Column({ type: 'varchar', length: 20 })
  status: MdCashCollectionRowStatus;

  @Column({ type: 'varchar', length: 20 })
  collected_by_type: MdCashCollectedByType;

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

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

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

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

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

  @Column({ type: 'timestamptz', nullable: true })
  collected_at: Date | null;

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