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

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

const toBoolean = ({ value }: { value: unknown }) => {
  if (typeof value === 'boolean') return value;
  if (value === 'true') return true;
  if (value === 'false') return false;
  return value;
};

export class CreateTruckTypeDto {
  @ApiProperty({ maxLength: 32, example: 'CASONI' })
  @IsString()
  @MaxLength(32)
  code!: string;

  @ApiProperty({ maxLength: 100, example: 'Casoni (rigid, no trailer)' })
  @IsString()
  @MaxLength(100)
  name!: string;

  @ApiPropertyOptional({
    description: 'Payload capacity in metric tons — pre-fills a vehicle registered against this type',
    example: 30,
  })
  @IsOptional()
  @Transform(toNumber)
  @IsNumber()
  @Min(0)
  capacityTons?: number;

  @ApiPropertyOptional({
    description: 'Whether this configuration pulls a trailer. False (e.g. Casoni) forbids a trailer plate.',
    default: false,
  })
  @IsOptional()
  @Transform(toBoolean)
  @IsBoolean()
  hasTrailer?: boolean;

  @ApiPropertyOptional()
  @IsOptional()
  @IsString()
  description?: string;

  @ApiPropertyOptional({ default: true })
  @IsOptional()
  @Transform(toBoolean)
  @IsBoolean()
  isActive?: boolean;
}
