using API.Contracts.Auth;
using API.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace API.Controllers.Auth
{
    [ApiController]
    [Route("auth")]
    public class AuthController(
        SignInManager<AppUser> signInManager,
        UserManager<AppUser> userManager)
        : ControllerBase
    {
        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<IActionResult> Login([FromBody] LoginRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.UserName) || string.IsNullOrWhiteSpace(request.Password))
                return BadRequest(new { message = "Benutzername und Passwort sind erforderlich." });

            var user = await userManager.FindByNameAsync(request.UserName);
            if (user is null)
                return Unauthorized(new { message = "Ungültige Anmeldedaten." });

            if (!user.IsActive)
                return Forbid();

            var result = await signInManager.PasswordSignInAsync(
                user,
                request.Password,
                isPersistent: true,
                lockoutOnFailure: false);

            if (!result.Succeeded)
                return Unauthorized(new { message = "Ungültige Anmeldedaten." });

            user.UpdatedAt = DateTimeOffset.UtcNow;
            await userManager.UpdateAsync(user);

            return Ok(new { message = "Login erfolgreich." });
        }

        [HttpPost("logout")]
        [Authorize]
        public async Task<IActionResult> Logout()
        {
            await signInManager.SignOutAsync();
            return Ok(new { message = "Logout erfolgreich." });
        }

        [HttpGet("me")]
        [Authorize]
        public async Task<ActionResult<CurrentUserResponse>> Me()
        {
            var user = await userManager.GetUserAsync(User);
            if (user is null)
                return Unauthorized();

            return Ok(new CurrentUserResponse
            {
                Id = user.Id,
                UserName = user.UserName ?? string.Empty,
                IsAdmin = user.IsAdmin,
                IsActive = user.IsActive,
                MustChangePassword = user.MustChangePassword
            });
        }
    }
}
