import { LeadStatus } from '@prisma/client';
import { IsDateString, IsEmail, IsIn, IsNotEmpty, IsNumber, IsOptional, IsString, IsUUID, Matches, Max, MaxLength, Min, ValidateIf } from 'class-validator';
import { EDITABLE_LEAD_STATUSES } from '../lead.constants';
import { NormalizeEmail, PHONE_MESSAGE, PHONE_PATTERN, Trim, TrimOrNull } from '../../../common/dto/field-transforms';

/** Fields of the prototype's lead form (FORMS.lead) plus job title, city and the IT field. */
export class CreateLeadDto {
  @Trim()
  @IsString()
  @IsNotEmpty({ message: 'Enter the full name' })
  @MaxLength(200)
  name!: string;

  @Trim()
  @IsString()
  @IsOptional()
  @MaxLength(255)
  company?: string;

  @TrimOrNull()
  @IsOptional()
  @ValidateIf((o: CreateLeadDto) => Boolean(o.email))
  @NormalizeEmail()
  @IsEmail({}, { message: 'Enter an email address like name@company.com' })
  @MaxLength(255)
  email?: string | null;

  @TrimOrNull()
  @IsOptional()
  @ValidateIf((o: CreateLeadDto) => Boolean(o.phone))
  @IsString()
  @Matches(PHONE_PATTERN, { message: PHONE_MESSAGE })
  @MaxLength(50)
  phone?: string | null;

  @TrimOrNull()
  @IsOptional()
  @IsString()
  @MaxLength(150)
  title?: string | null;

  @TrimOrNull()
  @IsOptional()
  @IsString()
  @MaxLength(100)
  city?: string | null;

  @TrimOrNull()
  @IsOptional()
  @IsString()
  @MaxLength(100)
  source?: string | null;

  @Trim()
  @IsString({ message: 'Select a service' })
  @IsNotEmpty({ message: 'Select a service' })
  @MaxLength(100)
  serviceInterest!: string;

  @IsOptional()
  @IsIn(EDITABLE_LEAD_STATUSES, {
    message: 'Status must be New, Contacted, Qualified, Nurturing or Unqualified',
  })
  status?: LeadStatus;

  @IsOptional()
  @IsNumber({ maxDecimalPlaces: 2 })
  @Min(0)
  @Max(999_999_999_999)
  estimatedValue?: number;

  /** Assigned user; defaults to the person creating the lead. */
  @IsOptional()
  @IsUUID()
  ownerId?: string | null;

  @IsOptional()
  @IsDateString()
  nextFollowUpAt?: string | null;
}
