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.CreateServiceCategory;

internal sealed class CreateServiceCategoryCommandHandler(IUnitOfWork unitOfWork, ICacheService cache)
    : IRequestHandler<CreateServiceCategoryCommand, OperationResult<ServiceCategoryDto>>
{
    public async ValueTask<OperationResult<ServiceCategoryDto>> Handle(CreateServiceCategoryCommand request, CancellationToken cancellationToken)
    {
        var category = new ServiceCategory
        {
            NameFa = request.NameFa,
            NameEn = request.NameEn,
            DescriptionFa = request.DescriptionFa,
            DescriptionEn = request.DescriptionEn,
            IconKey = request.IconKey,
            SortOrder = request.SortOrder,
            IsActive = true
        };

        await unitOfWork.CatalogRepository.AddCategoryAsync(category, cancellationToken);
        await unitOfWork.CommitAsync();

        await CatalogCache.InvalidateAsync(cache, cancellationToken);

        return OperationResult<ServiceCategoryDto>.SuccessResult(new ServiceCategoryDto(
            category.Id, category.NameFa, category.NameEn, category.DescriptionFa, category.DescriptionEn,
            category.IconKey, category.SortOrder, category.IsActive));
    }
}
