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 RegisterModel : PageModel
{
    private readonly IAuthService _authService;
    private readonly ILogger<RegisterModel> _logger;

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

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

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

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

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

    public string? ErrorMessage { get; set; }
    public string? SuccessMessage { 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(Email) || 
            string.IsNullOrWhiteSpace(Password) || string.IsNullOrWhiteSpace(ConfirmPassword))
        {
            ErrorMessage = "All fields are required";
            return Page();
        }

        var registerRequest = new RegisterRequest
        {
            Username = Username,
            Email = Email,
            Password = Password,
            ConfirmPassword = ConfirmPassword
        };

        var (success, token, error) = await _authService.RegisterAsync(registerRequest);

        if (!success || string.IsNullOrEmpty(token))
        {
            ErrorMessage = error ?? "Registration failed";
            _logger.LogWarning("Failed registration attempt for: {Username}", Username);
            return Page();
        }

        _logger.LogInformation("New account registered: {Username} ({Email})", Username, Email);

        // Auto-login after registration
        var loginRequest = new LoginRequest
        {
            UsernameOrEmail = Username,
            Password = Password
        };

        var (loginSuccess, response, loginError) = await _authService.LoginAsync(loginRequest);

        if (loginSuccess && response != null)
        {
            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,
                ExpiresUtc = response.ExpiresAt
            };

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

            return RedirectToPage("/Admin");
        }

        SuccessMessage = "Account created successfully! Please login.";
        return RedirectToPage("/Login");
    }
}
