using Lada.Framework.Data.Domains.Cms;
using Lada.Framework.Data.Repositories;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.EntityFrameworkCore;

namespace ladaexpress.vn.Infrastructures.Routes
{
    public class ProductRouteTransformer : DynamicRouteValueTransformer
    {
        //private readonly IBus _bus;
        private readonly IRepository<UrlRecord> _urlRecordRepository;
        public ProductRouteTransformer(IRepository<UrlRecord> urlRecordRepository)
        {

            _urlRecordRepository = urlRecordRepository;
        }

        public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
        {
            var controller = "Product";
            var action = "Index";
            var entityId = 0;


            if (!values.ContainsKey("slug"))
            {
                return values;
            }
            var requestPath = values["slug"].ToString();
            if (string.IsNullOrEmpty(requestPath)) return values;
            //var urlRecord = await _bus.Rpc.RequestAsync<string, UrlRecordDetail>(requestPath);
            var urlRecord = await _urlRecordRepository.Query().FirstOrDefaultAsync(u => u.Slug == $"dich-vu/{requestPath}");

            //var urlRecord = _urlRecordService.GetUrlRecordBySlug(requestPath);
            if (urlRecord != null && urlRecord.Id > 0)
            {
                action = "Detail";
                entityId = urlRecord.ProductId.HasValue ? urlRecord.ProductId.Value : 0;
            }
            else
            {
                controller = "Status";
                action = "NotFound";
            }

            values["controller"] = controller;
            values["action"] = action;
            values["id"] = entityId;
            return values;
        }
    }
}
