import { Transform, Type } from 'class-transformer'
import {
  IsEmail,
  IsEnum,
  IsInt,
  IsOptional,
  IsString,
  Max,
  MaxLength,
  Min,
  MinLength,
  ValidateNested,
} from 'class-validator'

// Coerce '' → undefined so blank form fields don't trip @IsEmail on the
// nested DTOs. @IsOptional() skips validation only for null/undefined, not
// empty strings — without this transform a partial edit fails the moment
// the form contains an unfilled email field.
const EmptyToUndefined = Transform(({ value }: { value: unknown }) =>
  value === '' ? undefined : value,
)

class ContactInfoDto {
  @IsOptional() @IsString() @MaxLength(200) primaryName?: string
  @EmptyToUndefined @IsOptional() @IsEmail() primaryEmail?: string
  @EmptyToUndefined @IsOptional() @IsEmail() billingEmail?: string
}

class BillingInfoDto {
  @IsOptional() @IsString() @MaxLength(200) companyName?: string
  @IsOptional() @IsString() @MaxLength(40) vatId?: string
  @IsOptional() @IsString() @MaxLength(2) country?: string
  @EmptyToUndefined @IsOptional() @IsEmail() contactEmail?: string
}

export class UpdatePartnerDto {
  @IsOptional() @IsString() @MinLength(2) @MaxLength(120)
  name?: string

  @IsOptional() @IsString() @MinLength(3) @MaxLength(120)
  domain?: string

  @IsOptional() @IsEnum(['active', 'in-negotiation', 'paused', 'terminated'])
  status?: 'active' | 'in-negotiation' | 'paused' | 'terminated'

  @IsOptional() @IsInt() @Min(0) @Max(100)
  marginPct?: number

  @IsOptional() @ValidateNested() @Type(() => ContactInfoDto)
  contactInfo?: ContactInfoDto

  @IsOptional() @ValidateNested() @Type(() => BillingInfoDto)
  billingInfo?: BillingInfoDto
}
