import { ApiProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsEmail, IsInt, IsOptional, IsString, Matches, Max, MaxLength, Min, MinLength } from 'class-validator';

const trim = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.trim() : value);
const lowerTrim = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.trim().toLowerCase() : value);

export class CreateCustomerDto {
    @ApiProperty({ example: 'Anil Verma' })
    @IsString()
    @MinLength(2)
    @MaxLength(80)
    @Transform(trim)
    name: string;

    @ApiProperty({ example: '9876043210', description: 'Mobile number, digits only' })
    @Matches(/^\d{7,15}$/)
    @Transform(trim)
    phone_no: string;

    @ApiProperty({ required: false, default: '+91' })
    @IsOptional()
    @Matches(/^\+\d{1,4}$/)
    @Transform(trim)
    country_code?: string;

    @ApiProperty({ required: false })
    @IsOptional()
    @IsEmail()
    @Transform(lowerTrim)
    email?: string;

    @ApiProperty({ required: false })
    @IsOptional()
    @IsString()
    @MaxLength(300)
    @Transform(trim)
    address?: string;
}

export class UpdateCustomerDto {
    @ApiProperty({ required: false })
    @IsOptional()
    @IsString()
    @MinLength(2)
    @MaxLength(80)
    @Transform(trim)
    name?: string;

    @ApiProperty({ required: false })
    @IsOptional()
    @Matches(/^\d{7,15}$/)
    @Transform(trim)
    phone_no?: string;

    @ApiProperty({ required: false })
    @IsOptional()
    @Matches(/^\+\d{1,4}$/)
    @Transform(trim)
    country_code?: string;

    @ApiProperty({ required: false })
    @IsOptional()
    @IsEmail()
    @Transform(lowerTrim)
    email?: string;

    @ApiProperty({ required: false })
    @IsOptional()
    @IsString()
    @MaxLength(300)
    @Transform(trim)
    address?: string;
}

export class CustomerListDto {
    @ApiProperty({ required: false, default: 1 })
    @IsOptional()
    @Transform(({ value }) => Number(value))
    @IsInt()
    @Min(1)
    page: number = 1;

    @ApiProperty({ required: false, default: 10 })
    @IsOptional()
    @Transform(({ value }) => Number(value))
    @IsInt()
    @Min(1)
    @Max(100)
    limit: number = 10;

    @ApiProperty({ required: false, description: 'Search by name, mobile or email' })
    @IsOptional()
    @IsString()
    search?: string;
}
