using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using QuantEngine.Core.Interfaces;
using QuantEngine.Core.Models;
using QuantEngine.Web.Services;

namespace QuantEngine.Web.Pages.Admin.Users;

[Authorize(AuthenticationSchemes = AdminAuthDefaults.Scheme)]
public class EditModel : PageModel
{
    private readonly IWorkspaceRepository _workspaceRepository;
    private readonly ILogger<EditModel> _logger;

    public WorkspaceAccount? CurrentUser { get; set; }

    [BindProperty]
    public EditUserInput Input { get; set; } = new();

    public EditModel(IWorkspaceRepository workspaceRepository, ILogger<EditModel> logger)
    {
        _workspaceRepository = workspaceRepository;
        _logger = logger;
    }

    public async Task<IActionResult> OnGetAsync(string username)
    {
        if (string.IsNullOrWhiteSpace(username))
            return NotFound();

        CurrentUser = await _workspaceRepository.GetAccountByUsernameAsync(username);
        if (CurrentUser == null)
            return NotFound();

        Input = new EditUserInput
        {
            Role = CurrentUser.Role ?? "Admin",
            IsActive = string.Equals(CurrentUser.IsActive, "true", StringComparison.OrdinalIgnoreCase)
        };

        return Page();
    }

    public async Task<IActionResult> OnPostAsync(string username)
    {
        CurrentUser = await _workspaceRepository.GetAccountByUsernameAsync(username);
        if (CurrentUser == null)
            return NotFound();

        if (!ModelState.IsValid)
            return Page();

        try
        {
            CurrentUser.Role = Input.Role;
            CurrentUser.IsActive = Input.IsActive ? "true" : "false";
            CurrentUser.UpdatedAt = DateTime.UtcNow.ToString("O");

            await _workspaceRepository.UpsertAccountAsync(CurrentUser);
            _logger.LogInformation("[Users] User updated: {Username}", username);

            return RedirectToPage("/Admin/Users/Index");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to update user");
            ModelState.AddModelError(string.Empty, "사용자 업데이트 중 오류가 발생했습니다.");
            return Page();
        }
    }
}

public class EditUserInput
{
    public string Role { get; set; } = "Admin";
    public bool IsActive { get; set; } = true;
}
