using FluentValidation;
using TakeoutSaaS.Application.App.Payments.Commands;
using TakeoutSaaS.Domain.Payments.Enums;

namespace TakeoutSaaS.Application.App.Payments.Validators;

/// <summary>
/// 创建支付记录命令验证器。
/// </summary>
public sealed class CreatePaymentCommandValidator : AbstractValidator<CreatePaymentCommand>
{
    /// <summary>
    /// 初始化验证规则。
    /// </summary>
    public CreatePaymentCommandValidator()
    {
        RuleFor(x => x.OrderId).GreaterThan(0);
        RuleFor(x => x.Amount).GreaterThan(0);
        RuleFor(x => x.Method)
            .Must(method => method != PaymentMethod.Unknown)
            .WithMessage("支付方式不可为空");
        RuleFor(x => x.TradeNo).MaximumLength(64);
        RuleFor(x => x.ChannelTransactionId).MaximumLength(64);
        RuleFor(x => x.Remark).MaximumLength(256);

        RuleFor(x => x.Status)
            .Must(status => status is PaymentStatus.Unpaid or PaymentStatus.Paying or PaymentStatus.Paid or PaymentStatus.Failed or PaymentStatus.Refunded)
            .WithMessage("支付状态不合法");
        When(x => x.Status == PaymentStatus.Paid, () =>
        {
            RuleFor(x => x.PaidAt).NotNull().WithMessage("支付成功必须包含支付时间");
        });
        When(x => x.Status != PaymentStatus.Paid, () =>
        {
            RuleFor(x => x.PaidAt).Must(paidAt => paidAt == null).WithMessage("非支付成功状态不应包含支付时间");
        });

        When(x => x.Method is PaymentMethod.Cash or PaymentMethod.Card or PaymentMethod.Balance, () =>
        {
            RuleFor(x => x.Status)
                .Must(status => status is not PaymentStatus.Paying)
                .WithMessage("线下/余额支付不允许处于 Paying 状态");
        });
    }
}
