namespace Netina.Repository.Handlers.ProductCategories;

public class CreateProductCategoryCommandHandler(IRepositoryWrapper repositoryWrapper,IMediator mediator,IMartenRepositoryWrapper martenRepositoryWrapper)
    : IRequestHandler<CreateProductCategoryCommand, Guid>
{
    public async Task<Guid> Handle(CreateProductCategoryCommand request, CancellationToken cancellationToken)
    {
        var ent = ProductCategory.Create(request.Name, request.Description, request.IsMain);
        if (request.ParentId != default)
            ent.SetParent(request.ParentId);
        foreach (var file in request.Files)
        {
            ent.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
        }
        repositoryWrapper.SetRepository<ProductCategory>().Add(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        await UpdateFaqAsync(ent, request.Faqs, cancellationToken);
        return ent.Id;
    }

    private async Task UpdateFaqAsync(ProductCategory newEnt, Dictionary<string, string> faqs, CancellationToken cancellationToken)
    {
        var url = newEnt.GetWebSiteUrl();
        var oldFaq = await martenRepositoryWrapper.SetRepository<BaseFaq>()
            .GetEntityAsync(f => f.Slug == newEnt.Slug, cancellationToken);
        var newFaq = await martenRepositoryWrapper.SetRepository<BaseFaq>()
            .GetEntityAsync(f => f.Slug == url, cancellationToken);
        if (oldFaq != null)
            await mediator.Send(new DeleteFaqCommand(oldFaq.Id), cancellationToken);

        if (newFaq == null)
            await mediator.Send(new CreateFaqCommand(faqs, url, newEnt.Name), cancellationToken);
        else
            await mediator.Send(new UpdateFaqCommand(newFaq.Id, faqs, url, newEnt.Name), cancellationToken);
    }
}