using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.IO;

namespace administration.Controllers
{
    public class PagesController : Controller
    {
        private readonly ICompositeViewEngine _viewEngine;
        private readonly ITempDataProvider _tempDataProvider;

        public PagesController(ICompositeViewEngine viewEngine, ITempDataProvider tempDataProvider)
        {
            _viewEngine = viewEngine;
            _tempDataProvider = tempDataProvider;
        }

        [HttpGet("/pages/{folder}/{page}")]
        public async Task<IActionResult> Render(string folder, string page)
        {
            var allowedFolders = new[] { "Charts", "Components", "Connections", "Home", "Tables", "Utilities" };

            var realFolder = allowedFolders.FirstOrDefault(f => string.Equals(f, folder, StringComparison.OrdinalIgnoreCase));
            if (realFolder == null)
                return Content("Ce dossier n'est pas autorisé.", "text/plain; charset=utf-8");

            // Trouver la vraie casse du fichier sur disque
            var folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Views", realFolder);
            var cshtmlFile = Directory.GetFiles(folderPath, "*.cshtml")
                                      .FirstOrDefault(f => string.Equals(Path.GetFileNameWithoutExtension(f), page, StringComparison.OrdinalIgnoreCase));

            if (cshtmlFile == null)
                return NotFound($"La vue ~/Views/{realFolder}/{page}.cshtml n'existe pas physiquement.");

            var razorViewPath = $"~/Views/{realFolder}/{Path.GetFileName(cshtmlFile)}";
            var result = _viewEngine.GetView(null, razorViewPath, true);

            if (!result.Success)
                return NotFound($"Vue Razor non trouvée : {razorViewPath}");


            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
            var tempData = new TempDataDictionary(HttpContext, _tempDataProvider);

            using var sw = new StringWriter();
            var context = new ViewContext(
                ControllerContext,
                result.View,
                viewData,
                tempData,
                sw,
                new HtmlHelperOptions()
            );

            await result.View.RenderAsync(context);
            return Content(sw.ToString(), "text/html");
        }
    }
}
