using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

[ApiController]
[Route("auth")]
public class AuthController : ControllerBase
{
    private readonly AuthService _auth;
    public AuthController(AuthService auth) => _auth = auth;

    // Form-Login: aus <form method="post" action="/auth/login?returnUrl=...">
    [AllowAnonymous]
    [HttpPost("login")]
    public async Task<IActionResult> Login([FromForm] string kassiererCode, [FromQuery] string? returnUrl)
    {
        var user = await _auth.ValidateAsync(kassiererCode ?? "");
        if (user is null)
            return Unauthorized("Ungültiger Code oder Benutzer inaktiv.");

        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, user.KassiererId.ToString()),
            new Claim(ClaimTypes.Name, $"{user.Vorname} {user.Nachname}"),
            new Claim("login", user.KassenLogin),
            new Claim("rollenId", user.RollenId.ToString())
        };

        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        var principal = new ClaimsPrincipal(identity);

        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

        // Nach Erfolg zurück zur gewünschten Seite
        if (string.IsNullOrWhiteSpace(returnUrl) || !Url.IsLocalUrl(returnUrl))
            return LocalRedirect("/");

        return LocalRedirect(returnUrl);
    }

    [Authorize]
    [HttpPost("/auth/logout")]
    public IActionResult Logout()
    {
        // Serverseitig abmelden
        HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

        // Antwort mit JS, das localStorage löscht und weiterleitet
        var html = """
            <!DOCTYPE html>
            <html lang="de">
            <head><meta charset="utf-8"><title>Logout</title></head>
            <body>
                <script>
                    try {
                        localStorage.removeItem("scannerpilot.filialId");
                        localStorage.removeItem("scannerpilot.inventurId");
                        localStorage.removeItem("scannerpilot.user");
                    } catch(e) { console.warn("localStorage cleanup failed", e); }
                    window.location.href = '/login';
                </script>
            </body>
            </html>
            """;

        return Content(html, "text/html");
    }
}
