using FluentValidation;
using TakeoutSaaS.Application.App.Finance.Cost.Queries;
using TakeoutSaaS.Domain.Finance.Enums;

namespace TakeoutSaaS.Application.App.Finance.Cost.Validators;

/// <summary>
/// 成本分析查询验证器。
/// </summary>
public sealed class GetFinanceCostAnalysisQueryValidator : AbstractValidator<GetFinanceCostAnalysisQuery>
{
    /// <summary>
    /// 初始化验证规则。
    /// </summary>
    public GetFinanceCostAnalysisQueryValidator()
    {
        RuleFor(x => x.Dimension)
            .Must(value => value is FinanceCostDimension.Tenant or FinanceCostDimension.Store)
            .WithMessage("dimension 非法");

        RuleFor(x => x)
            .Must(query =>
                query.Dimension != FinanceCostDimension.Store ||
                (query.StoreId.HasValue && query.StoreId.Value > 0))
            .WithMessage("storeId 非法");

        RuleFor(x => x.CostMonth)
            .Must(IsMonthInExpectedRange)
            .WithMessage("month 非法");

        RuleFor(x => x.TrendMonthCount)
            .InclusiveBetween(3, 12);
    }

    private static bool IsMonthInExpectedRange(DateTime value)
    {
        var month = value.Kind switch
        {
            DateTimeKind.Utc => value,
            DateTimeKind.Local => value.ToUniversalTime(),
            _ => DateTime.SpecifyKind(value, DateTimeKind.Utc)
        };

        return month.Year is >= 2000 and <= 2100;
    }
}
