import {
  IsArray,
  IsEmail,
  IsEnum,
  IsIn,
  IsInt,
  IsNotEmpty,
  IsOptional,
  IsString,
  IsUrl,
  MaxLength,
} from 'class-validator';
import { Type } from 'class-transformer';

import {
  ClientGroup,
  LeadPriority,
  LeadStatus,
  LEAD_SOURCES,
  LEAD_LOST_REASONS,
  SELECTABLE_CLIENT_GROUPS,
} from '../entities/lead.entity';

export class CreateLeadDto {
  @IsString()
  @IsNotEmpty()
  @MaxLength(255)
  company: string;

  /**
   * 🆕 Client group.
   *
   * Validated against SELECTABLE_CLIENT_GROUPS, not the full enum — so
   * QRS / TQS / QRS_NEW are accepted and the legacy QRS_B is rejected on
   * write while still being readable on old rows.
   *
   * To make it mandatory: delete the @IsOptional() line below. The column
   * stays nullable in the DB either way, which keeps legacy rows valid.
   */
  @IsOptional()
  @IsIn(SELECTABLE_CLIENT_GROUPS as readonly string[], {
    message: `client_group must be one of: ${SELECTABLE_CLIENT_GROUPS.join(', ')}`,
  })
  client_group?: ClientGroup;

  @IsOptional()
  @IsString()
  @MaxLength(255)
  contact?: string;

  @IsOptional()
  @IsString()
  @MaxLength(255)
  phone?: string;

  @IsOptional()
  @IsEmail()
  @MaxLength(255)
  email?: string;

  @IsOptional()
  @IsUrl()
  @MaxLength(255)
  website?: string;

  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  standards?: string[];

  // Excludes 'Converted' — that's only reachable via the dedicated
  // convert-to-client flow, same restriction as the Laravel form.
  @IsOptional()
  @IsIn([LeadStatus.NEW, LeadStatus.INTERESTED, LeadStatus.LOST])
  status?: LeadStatus;

  @IsOptional()
  @IsIn(LEAD_LOST_REASONS)
  lost_reason?: string;

  @IsOptional()
  @IsString()
  @MaxLength(2000)
  lost_notes?: string;

  @IsOptional()
  @IsIn(LEAD_SOURCES)
  source?: string;

  @IsOptional()
  @IsEnum(LeadPriority)
  priority?: LeadPriority;

  @IsOptional()
  @IsString()
  @MaxLength(4000)
  notes?: string;

  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  tags?: string[];

  @IsOptional()
  @IsInt()
  @Type(() => Number)
  assigned_to?: number;

  // Set true to bypass a detected duplicate and save anyway.
  @IsOptional()
  override_duplicate?: boolean;
}
