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

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

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

  @ApiPropertyOptional({ example: 'user@example.com' })
  @IsOptional()
  @IsEmail()
  email?: string;

  @ApiPropertyOptional({ example: 'User@12345', minLength: 8 })
  @IsOptional()
  @IsString()
  @MinLength(8)
  password?: string;

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

  @ApiPropertyOptional({
    example: true,
    description:
      'true = Active, false = Inactive. Backend stores this with deletedAt.',
  })
  @IsOptional()
  @Transform(({ value }: { value: unknown }) => {
    if (value === true || value === 'true') return true;
    if (value === false || value === 'false') return false;

    return value;
  })
  @IsBoolean()
  isActive?: boolean;

  @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 the user should have. Replaces the current set (empty array clears all). Omit to leave roles unchanged.',
  })
  @IsOptional()
  @Transform(({ value }: { value: unknown }) => parseRoleIds(value))
  @IsArray()
  @ArrayUnique()
  @IsInt({ each: true })
  @IsPositive({ each: true })
  roleIds?: number[];
}
