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

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

internal sealed class UpdateServiceOptionGroupCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<UpdateServiceOptionGroupCommand, OperationResult<OptionGroupDto>>
{
    public async ValueTask<OperationResult<OptionGroupDto>> Handle(UpdateServiceOptionGroupCommand request, CancellationToken cancellationToken)
    {
        var group = await unitOfWork.CatalogRepository.GetGroupAsync(request.Id, cancellationToken);
        if (group is null)
            return OperationResult<OptionGroupDto>.NotFoundResult("Option group not found.");

        if (request.ServiceCategoryId is { } categoryId
            && !await unitOfWork.CatalogRepository.CategoryExistsAsync(categoryId, cancellationToken))
            return OperationResult<OptionGroupDto>.FailureResult(nameof(request.ServiceCategoryId), "Category not found.");

        group.ServiceCategoryId = request.ServiceCategoryId;
        group.NameFa = request.NameFa;
        group.NameEn = request.NameEn;
        group.IsRequired = request.IsRequired;
        group.SortOrder = request.SortOrder;

        await unitOfWork.CommitAsync();
        await CatalogCache.InvalidateAsync(cache, cancellationToken);

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