using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Watcher.Data;
using Watcher.ViewModels;

namespace Watcher.Controllers;

public class AuthController : Controller
{
    private readonly AppDbContext _context;
    private readonly ILogger<AuthController> _logger;

    public AuthController(AppDbContext context, ILogger<AuthController> logger)
    {
        _context = context;
        _logger = logger;
    }


    // Login Seite anzeigen
    [HttpGet("/Auth/Login")]
    public IActionResult Login(string? returnUrl = null)
    {
        var model = new LoginViewModel
        {
            ReturnUrl = returnUrl
        };

        return View(model);
    }


    // Login mit lokalem User
    [HttpPost]
    public async Task<IActionResult> Login(LoginViewModel model)
    {
        if (!ModelState.IsValid)
            return View(model);

        try
        {
            var user = await _context.Users.FirstOrDefaultAsync(u => u.Username == model.Username);
            if (user == null || !BCrypt.Net.BCrypt.Verify(model.Password, user.Password))
            {
                ModelState.AddModelError("", "Benutzername oder Passwort ist falsch.");
                return View(model);
            }

            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.Username),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            };

            var identity = new ClaimsIdentity(claims, "local");
            var principal = new ClaimsPrincipal(identity);

            await HttpContext.SignInAsync("Cookies", principal);

            _logger.LogInformation("lokaler User angemeldet: " + user.Username);

            return Redirect("/");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Fehler beim Login. User: {UserName}", model.Username);
            ModelState.AddModelError("", "Es ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.");
            return View(model);
        }        
    }


    // Logout
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync("Cookies");

        _logger.LogInformation("User abgemeldet");

        return RedirectToAction("Login", "Auth");
    }
}
