import { BadRequestException } from '@nestjs/common';

/**
 * Email Value Object
 * 邮箱值对象 — 格式校验 + 归一化（小写）+ 脱敏展示
 */
export class Email {
  private static readonly PATTERN =
    /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;

  private constructor(public readonly value: string) {}

  /**
   * 创建并校验 Email
   * @param raw 原始输入（自动 trim + lowercase）
   * @throws BadRequestException 格式无效
   */
  static create(raw: string): Email {
    const normalized = raw.trim().toLowerCase();
    if (!Email.PATTERN.test(normalized)) {
      throw new BadRequestException('邮箱格式无效');
    }
    return new Email(normalized);
  }

  /**
   * 脱敏展示: user@example.com → u***@example.com
   */
  get masked(): string {
    const atIndex = this.value.indexOf('@');
    const local = this.value.slice(0, atIndex);
    const domain = this.value.slice(atIndex);
    const maskedLocal = local.length > 1
      ? local[0] + '***'
      : '***';
    return `${maskedLocal}${domain}`;
  }

  toString(): string {
    return this.value;
  }
}
