using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

namespace PowderCoating.Web.Controllers;

/// <summary>
/// Handles the application root URL and static informational pages
/// (Privacy, Terms of Service, SLA, DPA, Security, Accessibility).
/// Also provides the global error handler endpoint used by the exception
/// handling middleware pipeline.
/// </summary>
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }
    /// <summary>
    /// Handles requests to the application root (<c>/</c>).  Authenticated users are
    /// immediately redirected to the Dashboard; unauthenticated visitors are sent to
    /// the Identity login page.  This ensures no content is ever rendered at the root
    /// URL — the root is purely a routing decision point.
    /// </summary>
    public IActionResult Index()
    {
        if (User.Identity?.IsAuthenticated == true)
        {
            return RedirectToAction("Index", "Dashboard");
        }

        // Otherwise redirect to the login page
        return Redirect("/Identity/Account/Login");
    }

    /// <summary>Renders the Privacy Policy static page.</summary>
    public IActionResult Privacy()
    {
        return View();
    }

    /// <summary>Renders the Terms of Service static page.</summary>
    public IActionResult TermsOfService()
    {
        return View();
    }

    /// <summary>Renders the Service Level Agreement static page.</summary>
    public IActionResult ServiceLevelAgreement()
    {
        return View();
    }

    /// <summary>Renders the Data Processing Addendum (DPA) static page.</summary>
    public IActionResult DataProcessingAddendum()
    {
        return View();
    }

    /// <summary>Renders the Security overview static page.</summary>
    public IActionResult Security()
    {
        return View();
    }

    /// <summary>Renders the Accessibility statement static page.</summary>
    public IActionResult Accessibility()
    {
        return View();
    }

    /// <summary>
    /// Global error handler endpoint — invoked by the ASP.NET Core exception handling
    /// middleware when an unhandled exception propagates out of any controller.
    /// Logs the exception with path, user identity, and trace Id for structured
    /// log correlation, then renders a user-friendly error view.
    /// Response caching is disabled (<c>NoStore</c>) to prevent error pages from
    /// being cached and served to subsequent requests without a real error.
    /// </summary>
    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        // Get the exception details from the exception handler
        var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

        if (exceptionHandlerPathFeature?.Error != null)
        {
            var exception = exceptionHandlerPathFeature.Error;
            var path = exceptionHandlerPathFeature.Path;

            _logger.LogError(exception,
                "Unhandled exception occurred. Path: {Path}, User: {User}, TraceId: {TraceId}",
                path,
                User.Identity?.Name ?? "Anonymous",
                HttpContext.TraceIdentifier);
        }

        return View();
    }
}
