using System.Net;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WerksverkaufScanner.Services; // <-- für IpFilialeService

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

    public AuthController(AuthService auth, IpFilialeService ipFiliale)
    {
        _auth = auth;
        _ipFiliale = ipFiliale;
    }

    // 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 ?? string.Empty);
        if (user is null)
            return Unauthorized("Ungültiger Code oder Benutzer inaktiv.");

        // 1) Client-IP ermitteln (Reverse-Proxy: X-Forwarded-For beachten)


#if DEBUG
        var clientIp = IPAddress.Parse("192.168.118.5");
#else
        var clientIp = GetClientIp(HttpContext);
#endif


        // 2) IP -> FilialId (optional)
        int? filialId = null;
        if (clientIp != null)
            filialId = await _ipFiliale.TryMatchFilialeAsync(clientIp);

        // 3) Claims zusammenstellen
        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())
        };

        if (filialId.HasValue)
            claims.Add(new Claim("filialId", filialId.Value.ToString()));

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

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

        // 4) Zurück zur Zielseite
        if (string.IsNullOrWhiteSpace(returnUrl) || !Url.IsLocalUrl(returnUrl))
            return LocalRedirect("/");

        return LocalRedirect(returnUrl);
    }

    [Authorize]
    [HttpPost("/auth/logout")]
    public async Task<IActionResult> Logout()
    {
        // Serverseitig abmelden (await nicht vergessen!)
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

        // Client: localStorage aufräumen & weiterleiten
        const string 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");
    }

    private static IPAddress? GetClientIp(HttpContext ctx)
    {
        // Falls hinter Reverse-Proxy: erstes X-Forwarded-For nehmen
        var xff = ctx.Request.Headers["X-Forwarded-For"].FirstOrDefault();
        if (!string.IsNullOrWhiteSpace(xff))
        {
            var first = xff.Split(',').Select(s => s.Trim()).FirstOrDefault();
            if (IPAddress.TryParse(first, out var ipFromHeader))
                return ipFromHeader;
        }

        return ctx.Connection.RemoteIpAddress;
    }
}
