import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import {
  ArrayUnique,
  IsArray,
  IsEmail,
  IsInt,
  IsOptional,
  IsPositive,
  IsString,
  IsUrl,
  MaxLength,
  MinLength,
} from 'class-validator';

import { parseRoleIds } from './role-ids.transform';

export class CreateUserDto {
  @ApiProperty({ example: 'user@example.com' })
  @IsEmail()
  email!: string;

  @ApiProperty({ example: 'User@12345', minLength: 8 })
  @IsString()
  @MinLength(8)
  password!: string;

  @ApiPropertyOptional({ example: 'Alice Smith' })
  @IsOptional()
  @IsString()
  @MinLength(1)
  @MaxLength(120)
  name?: string;

  @ApiPropertyOptional({ example: 'Director of Operations' })
  @IsOptional()
  @IsString()
  @MaxLength(120)
  position?: string;

  @ApiPropertyOptional({
    example: 'https://cdn.example.com/avatars/user-123.png',
  })
  @IsOptional()
  @IsString()
  @IsUrl()
  @MaxLength(2048)
  avatar?: string;

  @ApiPropertyOptional({
    type: 'string',
    format: 'binary',
    description: 'Avatar image file. Use form-data key: avatarFile',
  })
  @IsOptional()
  avatarFile?: unknown;

  @ApiPropertyOptional({
    type: [Number],
    example: [1, 2],
    description:
      'IDs of roles to assign to the new user. JSON array, or a comma-separated / JSON string for multipart form-data.',
  })
  @IsOptional()
  @Transform(({ value }: { value: unknown }) => parseRoleIds(value))
  @IsArray()
  @ArrayUnique()
  @IsInt({ each: true })
  @IsPositive({ each: true })
  roleIds?: number[];
}
