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 IndexModel : PageModel
{
    private readonly IWorkspaceRepository _workspaceRepository;
    private readonly ILogger<IndexModel> _logger;

    public List<WorkspaceAccount>? Users { get; set; }

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

    public async Task OnGetAsync()
    {
        await LoadUsers();
    }

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

        try
        {
            var account = await _workspaceRepository.GetAccountByUsernameAsync(username);
            if (account == null)
                return NotFound();

            account.IsActive = "false";
            account.UpdatedAt = DateTime.UtcNow.ToString("O");
            await _workspaceRepository.UpsertAccountAsync(account);
            _logger.LogInformation("[Users] User deactivated: {Username}", username);

            return RedirectToPage();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "User deactivation failed: {Username}", username);
            ModelState.AddModelError(string.Empty, "사용자 비활성화 중 오류가 발생했습니다.");
            await LoadUsers();
            return Page();
        }
    }

    private async Task LoadUsers()
    {
        try
        {
            var accounts = await _workspaceRepository.GetAccountsAsync();
            Users = accounts.ToList();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Users loading failed");
        }
    }
}
