using System.Globalization;
using Baya.Domain.Entities.Catalog;
using FluentValidation;

namespace Baya.Application.Features.Variants.Commands.CreateVariant;

public sealed class CreateVariantCommandValidator : AbstractValidator<CreateVariantCommand>
{
    public CreateVariantCommandValidator()
    {
        RuleFor(x => x.ServiceCategoryId).GreaterThan(0);

        // Money is a string of IRR-Rial digits — positive integer, no sign/decimal/whitespace, no overflow.
        RuleFor(x => x.Price)
            .NotEmpty()
            .Must(BePositiveIrrAmount)
            .WithMessage("Price must be a positive integer number of IRR Rials (digits only).");

        RuleFor(x => x.PriceUnit)
            .Must(PriceUnits.IsValid)
            .WithMessage("price_unit must be one of: per_hour, per_session, per_half_day, per_day, per_24h.");

        RuleFor(x => x.SessionCount).GreaterThan(0).When(x => x.SessionCount.HasValue);

        RuleFor(x => x.DisplayName).MaximumLength(300);

        // The required-group / one-value-per-dimension / value-belongs-to-group rules need the catalog, so
        // they live in the handler (clean OperationResult). Here we only enforce the shape.
        RuleFor(x => x.Options).NotNull();
        RuleForEach(x => x.Options).ChildRules(o =>
        {
            o.RuleFor(s => s.OptionGroupId).GreaterThan(0);
            o.RuleFor(s => s.OptionValueId).GreaterThan(0);
        });
    }

    private static bool BePositiveIrrAmount(string value)
        => long.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var amount) && amount > 0;
}
