using FluentValidation;
using MembershipService.API.Application.Commands;

namespace MembershipService.API.Application.Validations;

/// <summary>
/// EN: Validator for UpdateMemberProfileCommand.
/// VI: Validator cho UpdateMemberProfileCommand.
/// </summary>
public class UpdateMemberProfileCommandValidator : AbstractValidator<UpdateMemberProfileCommand>
{
    public UpdateMemberProfileCommandValidator()
    {
        RuleFor(x => x.MemberId)
            .NotEmpty()
            .WithMessage("MemberId is required");

        RuleFor(x => x.Gender)
            .MaximumLength(10)
            .Must(BeAValidGender)
            .When(x => !string.IsNullOrEmpty(x.Gender))
            .WithMessage("Gender must be Male, Female, or Other");

        RuleFor(x => x.CountryCode)
            .Length(2)
            .When(x => !string.IsNullOrEmpty(x.CountryCode))
            .WithMessage("CountryCode must be 2 characters");

        RuleFor(x => x.Preferences)
            .Must(BeValidJson)
            .When(x => !string.IsNullOrEmpty(x.Preferences))
            .WithMessage("Preferences must be valid JSON");
    }

    private static bool BeAValidGender(string? gender)
    {
        if (string.IsNullOrEmpty(gender)) return true;
        var validGenders = new[] { "Male", "Female", "Other" };
        return validGenders.Contains(gender, StringComparer.OrdinalIgnoreCase);
    }

    private static bool BeValidJson(string? json)
    {
        if (string.IsNullOrEmpty(json)) return true;
        try
        {
            System.Text.Json.JsonDocument.Parse(json);
            return true;
        }
        catch
        {
            return false;
        }
    }
}
