import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsIn, IsNumber, IsOptional, IsUUID, Min } from 'class-validator';

import { LAST_MILE_STATUSES, LastMileStatus } from '../entities/last-mile.entity';

const toNumber = ({ value }: { value: unknown }) =>
  value === '' || value == null ? undefined : Number(value);

export class CreateLastMileDto {
  @ApiProperty({ description: 'Booking this last-mile leg belongs to (FK → bookings.id)' })
  @IsUUID()
  bookingId!: string;

  @ApiPropertyOptional({
    enum: LAST_MILE_STATUSES,
    default: 'PAYMENT_PENDING',
  })
  @IsOptional()
  @IsIn(LAST_MILE_STATUSES as unknown as string[])
  status?: LastMileStatus;

  @ApiPropertyOptional({ description: 'Amount already paid in advance', example: 4200 })
  @IsOptional()
  @Transform(toNumber)
  @IsNumber()
  @Min(0)
  advancedPayment?: number;

  @ApiPropertyOptional({ description: 'Outstanding balance to be collected', example: 1800 })
  @IsOptional()
  @Transform(toNumber)
  @IsNumber()
  @Min(0)
  remainingPayment?: number;

  @ApiPropertyOptional({ description: 'Planned distance for the leg, in km', example: 42.5 })
  @IsOptional()
  @Transform(toNumber)
  @IsNumber()
  @Min(0)
  estimatedKm?: number;

  @ApiPropertyOptional({ description: 'Actual distance travelled, in km', example: 44.1 })
  @IsOptional()
  @Transform(toNumber)
  @IsNumber()
  @Min(0)
  exactKm?: number;

  @ApiPropertyOptional({
    type: String,
    format: 'uuid',
    description: 'Assigned vehicle (FK → vehicles.id). May be null until assigned.',
    nullable: true,
  })
  @IsOptional()
  @Transform(({ value }) => (value === '' ? undefined : value))
  @IsUUID()
  vehicleId?: string | null;
}
