using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.App.Personal.Validators;

/// <summary>
/// 个人中心通用时间范围校验器。
/// </summary>
public sealed class PersonalDateRangeValidator
{
    private const int DefaultDays = 90;
    private const int MaxRangeDays = 365;

    /// <summary>
    /// 解析并校验时间范围。
    /// </summary>
    /// <param name="from">起始时间。</param>
    /// <param name="to">截止时间。</param>
    /// <returns>校验后的起止时间（UTC）。</returns>
    public (DateTime From, DateTime To) Resolve(DateTime? from, DateTime? to)
    {
        // 1. 计算默认时间窗
        var utcNow = DateTime.UtcNow;
        var resolvedTo = to?.ToUniversalTime() ?? utcNow;
        var resolvedFrom = from?.ToUniversalTime() ?? resolvedTo.AddDays(-DefaultDays);

        // 2. 校验起止先后关系
        if (resolvedFrom > resolvedTo)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "时间范围非法：from 不能大于 to");
        }

        // 3. 校验跨度上限
        var spanDays = (resolvedTo - resolvedFrom).TotalDays;
        if (spanDays > MaxRangeDays)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, $"时间范围非法：跨度不能超过 {MaxRangeDays} 天");
        }

        // 4. 返回校验后的时间范围
        return (resolvedFrom, resolvedTo);
    }
}
