import {
  IsIn,
  IsNotEmpty,
  IsNumber,
  IsOptional,
  IsString,
  IsUUID,
  Matches,
  MaxLength,
  Min,
  ValidateIf,
} from 'class-validator';

/**
 * Create or replace the live cash collection on a Movement Chart route
 * (transport / activity / special item).
 *
 * OWN → collector_name required; supplier/driver/activity omitted.
 * SUPPLIER → supplier_id + source_kind required; driver_id OR a typed
 * driver_name (find-or-create on that supplier).
 */
export class UpsertBookingCashCollectionDto {
  @IsUUID()
  booking_id: string;

  @IsString()
  @Matches(/^\d{4}-\d{2}-\d{2}$/)
  collection_date: string;

  @IsOptional()
  @IsUUID()
  transport_item_id?: string;

  @IsOptional()
  @IsUUID()
  activity_item_id?: string;

  @IsOptional()
  @IsUUID()
  special_item_id?: string;

  @IsUUID()
  currency_id: string;

  @IsNumber({ maxDecimalPlaces: 2 })
  @Min(0.01)
  expected_amount: number;

  @IsOptional()
  @IsString()
  @MaxLength(1000)
  notes?: string | null;

  @IsIn(['OWN', 'SUPPLIER'])
  collected_by_type: 'OWN' | 'SUPPLIER';

  @ValidateIf((o: UpsertBookingCashCollectionDto) => o.collected_by_type === 'OWN')
  @IsString()
  @IsNotEmpty()
  @MaxLength(255)
  collector_name?: string;

  @ValidateIf((o: UpsertBookingCashCollectionDto) => o.collected_by_type === 'SUPPLIER')
  @IsUUID()
  supplier_id?: string;

  @ValidateIf((o: UpsertBookingCashCollectionDto) => o.collected_by_type === 'SUPPLIER')
  @IsIn(['TRANSPORT', 'ACTIVITY', 'SPECIAL'])
  source_kind?: 'TRANSPORT' | 'ACTIVITY' | 'SPECIAL';

  @IsOptional()
  @IsUUID()
  activity_id?: string;

  @IsOptional()
  @IsUUID()
  driver_id?: string;

  @ValidateIf(
    (o: UpsertBookingCashCollectionDto) =>
      o.collected_by_type === 'SUPPLIER' && !o.driver_id,
  )
  @IsString()
  @IsNotEmpty()
  @MaxLength(255)
  driver_name?: string;
}
