using System.Net.Mail;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Options;
using Watcher.Data;
using Watcher.ViewModels;

namespace Watcher.Controllers;

public class AppSettings
{
    public Boolean oidc { get; set; }
}

public class AuthController : Controller
{
    private readonly AppDbContext _context;
    private readonly AppSettings _settings;

    // Logging einbinden
    private readonly ILogger<AuthController> _logger;


    public AuthController(AppDbContext context, IOptions<AppSettings> options, ILogger<AuthController> logger)
    {
        _context = context;
        _settings = options.Value;
        _logger = logger;
    }


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

        ViewBag.oidc = _settings.oidc;
        return View(model);
    }


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

        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();
        }

        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("Home/Index");
    }


    // Login mit OIDC-Provider
    public IActionResult SignIn()
    {
        return Challenge(new AuthenticationProperties
        {
            RedirectUri = "/Home/Index"
        }, "oidc");
    }



    // Logout
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Logout()
    {
        var props = new AuthenticationProperties
        {
            RedirectUri = Url.Action("Login", "Auth")
        };

        await HttpContext.SignOutAsync("Cookies");
        await HttpContext.SignOutAsync("oidc", props);

        _logger.LogInformation("User abgemeldet");

        return Redirect("/"); // nur als Fallback
    }




}
