using Netina.Domain.Entities.Brands;

namespace Netina.Repository.Handlers.Brands;

public class CreateBrandCommandHandler(IRepositoryWrapper repositoryWrapper,IMartenRepositoryWrapper martenRepositoryWrapper , IMediator mediator) : IRequestHandler<CreateBrandCommand, Guid>
{
    public async Task<Guid> Handle(CreateBrandCommand request, CancellationToken cancellationToken)
    {
        var ent = Brand.Create(request.PersianName,request.EnglishName, request.Description, request.HasSpecialPage, request.PageUrl);
        foreach (var file in request.Files)
        {
            ent.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
        }
        repositoryWrapper.SetRepository<Brand>().Add(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);

        await UpdateFaqAsync(ent, request.Faqs, cancellationToken);

        return ent.Id;
    }


    private async Task UpdateFaqAsync(Brand 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.EnglishName), cancellationToken);
        else
            await mediator.Send(new UpdateFaqCommand(newFaq.Id, faqs, url, newEnt.EnglishName), cancellationToken);
    }
}