namespace Netina.Repository.Handlers.Products;

public class CreateProductCommandHandler(IRepositoryWrapper repositoryWrapper,IMartenRepositoryWrapper martenRepositoryWrapper, IMediator mediator,ICurrentUserService currentUserService)
    : IRequestHandler<CreateProductCommand, ProductLDto>
{
    public async Task<ProductLDto> Handle(CreateProductCommand request, CancellationToken cancellationToken)
    {

        if (currentUserService.UserId == null)
            throw new BaseApiException(ApiResultStatusCode.UnAuthorized, "User id is wrong");
        if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
            throw new BaseApiException(ApiResultStatusCode.UnAuthorized, "User id is wrong");

        var ent = Product.Create(request.PersianName, request.EnglishName, request.Summery, request.ExpertCheck,
            request.Tags, request.Warranty,request.BeDisplayed,request.Cost,request.PackingCost,
            request.HasExpressDelivery,
            request.Stock,
            request.MaxOrderCount,
            request.BrandId,request.CategoryId, userId);

        foreach (var specification in request.Specifications)
        {
            ent.AddSpecification(specification.Title, specification.Detail, specification.Value,
                specification.IsFeature, specification.ParentId);
        }

        foreach (var file in request.Files)
        {
            ent.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
        }

        

        repositoryWrapper.SetRepository<Product>().Add(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);

        if (request.IsSpecialOffer)
        {
            var discount = request.SpecialOffer.Adapt<DiscountLDto>();
            discount.ProductId = ent.Id;
            discount.IsSpecialOffer = true;
            discount.Type = DiscountType.Product;
            discount.HasCode = false;
            discount.IsInfinity = true;
            if (request.SpecialOffer.Id == default)
            {
                var discountRequest = discount.Adapt<CreateDiscountCommand>();
                await mediator.Send(discountRequest, cancellationToken);
            }
            else
            {
                var discountRequest = discount.Adapt<UpdateDiscountCommand>();
                await mediator.Send(discountRequest, cancellationToken);
            }
        }

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

        return ent.AdaptToLDto();
    }


    private async Task UpdateFaqAsync(Product 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);
    }
}