using System.Diagnostics;
using System.Security.Claims;
using administration.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace administration.Controllers
{
    [Authorize] // toute la classe nécessite une connexion
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            EnsureSessionFromClaims();
            return View();
        }

        public IActionResult Profile()
        {
            EnsureSessionFromClaims();

            ViewBag.UserId = HttpContext.Session.GetInt32("UserId");
            ViewBag.UserName = HttpContext.Session.GetString("UserName");

            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        /// <summary>
        /// Si la session est vide, recharge UserId et UserName depuis les claims
        /// </summary>
        private void EnsureSessionFromClaims()
        {
            if (!HttpContext.Session.Keys.Contains("UserId") || !HttpContext.Session.Keys.Contains("UserName"))
            {
                var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
                var userNameClaim = User.FindFirstValue(ClaimTypes.Name);

                if (!string.IsNullOrEmpty(userIdClaim) && int.TryParse(userIdClaim, out int userId))
                {
                    HttpContext.Session.SetInt32("UserId", userId);
                }

                if (!string.IsNullOrEmpty(userNameClaim))
                {
                    HttpContext.Session.SetString("UserName", userNameClaim);
                }
            }
        }
    }
}
