using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Catalog;
using Baya.Application.Models.Common;
using Baya.Domain.Entities.Catalog;
using Mediator;

namespace Baya.Application.Features.Catalog.Commands.CreateServiceOptionGroup;

internal sealed class CreateServiceOptionGroupCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<CreateServiceOptionGroupCommand, OperationResult<OptionGroupDto>>
{
    public async ValueTask<OperationResult<OptionGroupDto>> Handle(CreateServiceOptionGroupCommand request, CancellationToken cancellationToken)
    {
        if (request.ServiceCategoryId is { } categoryId
            && !await unitOfWork.CatalogRepository.CategoryExistsAsync(categoryId, cancellationToken))
            return OperationResult<OptionGroupDto>.FailureResult(nameof(request.ServiceCategoryId), "Category not found.");

        var group = new ServiceOptionGroup
        {
            ServiceCategoryId = request.ServiceCategoryId,
            NameFa = request.NameFa,
            NameEn = request.NameEn,
            IsRequired = request.IsRequired,
            SortOrder = request.SortOrder,
            IsActive = true
        };

        await unitOfWork.CatalogRepository.AddGroupAsync(group, cancellationToken);
        await unitOfWork.CommitAsync();

        await CatalogCache.InvalidateAsync(cache, cancellationToken);

        var dto = await unitOfWork.CatalogRepository.GetGroupDtoAsync(group.Id, cancellationToken);
        return OperationResult<OptionGroupDto>.SuccessResult(dto!);
    }
}
