using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;
using RR3CommunityServer.Services;
using RR3CommunityServer.Models;

namespace RR3CommunityServer.Pages;

public class LoginModel : PageModel
{
    private readonly IAuthService _authService;
    private readonly ILogger<LoginModel> _logger;

    public LoginModel(IAuthService authService, ILogger<LoginModel> logger)
    {
        _authService = authService;
        _logger = logger;
    }

    [BindProperty]
    public string Username { get; set; } = string.Empty;

    [BindProperty]
    public string Password { get; set; } = string.Empty;

    public string? ErrorMessage { get; set; }

    public void OnGet()
    {
        // If already logged in, redirect to admin panel
        if (User.Identity?.IsAuthenticated == true)
        {
            Response.Redirect("/admin");
        }
    }

    public async Task<IActionResult> OnPostAsync()
    {
        if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password))
        {
            ErrorMessage = "Username and password are required";
            return Page();
        }

        var loginRequest = new LoginRequest
        {
            UsernameOrEmail = Username,
            Password = Password
        };

        var (success, response, error) = await _authService.LoginAsync(loginRequest);

        if (!success || response == null)
        {
            ErrorMessage = error ?? "Invalid username or password";
            _logger.LogWarning("Failed login attempt for: {Username}", Username);
            return Page();
        }

        // Create authentication cookie
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, response.AccountId.ToString()),
            new Claim(ClaimTypes.Name, response.Username),
            new Claim(ClaimTypes.Email, response.Email)
        };

        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        var authProperties = new AuthenticationProperties
        {
            IsPersistent = true, // Remember me
            ExpiresUtc = response.ExpiresAt
        };

        await HttpContext.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(claimsIdentity),
            authProperties);

        _logger.LogInformation("User logged in to admin panel: {Username}", response.Username);

        return RedirectToPage("/Admin");
    }
}
