namespace TakeoutSaaS.Application.App.Personal.Services;

/// <summary>
/// 个人中心敏感信息脱敏服务。
/// </summary>
public sealed class PersonalMaskingService
{
    /// <summary>
    /// 手机号脱敏。
    /// </summary>
    /// <param name="phone">原始手机号。</param>
    /// <returns>脱敏手机号。</returns>
    public string? MaskPhone(string? phone)
    {
        // 1. 空值直接返回
        if (string.IsNullOrWhiteSpace(phone))
        {
            return null;
        }

        // 2. 长度不足时按固定策略脱敏
        if (phone.Length < 7)
        {
            return $"{phone[..1]}***";
        }

        // 3. 标准手机号保留前三后四
        return $"{phone[..3]}****{phone[^4..]}";
    }

    /// <summary>
    /// 邮箱脱敏。
    /// </summary>
    /// <param name="email">原始邮箱。</param>
    /// <returns>脱敏邮箱。</returns>
    public string? MaskEmail(string? email)
    {
        // 1. 空值直接返回
        if (string.IsNullOrWhiteSpace(email))
        {
            return null;
        }

        // 2. 非法格式按通用策略脱敏
        var atIndex = email.IndexOf('@');
        if (atIndex <= 0 || atIndex == email.Length - 1)
        {
            return "***";
        }

        // 3. 合法邮箱保留首尾字符和域名
        var localPart = email[..atIndex];
        var domainPart = email[atIndex..];
        if (localPart.Length == 1)
        {
            return $"{localPart[0]}***{domainPart}";
        }

        return $"{localPart[0]}***{localPart[^1]}{domainPart}";
    }
}
