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;
using BCrypt.Net;
using System.ComponentModel.DataAnnotations;

namespace QuantEngine.Web.Pages.Admin.Users;

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

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

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

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
            return Page();

        if (string.IsNullOrWhiteSpace(Input.Username) || string.IsNullOrWhiteSpace(Input.Password))
        {
            ModelState.AddModelError(string.Empty, "사용자명과 비밀번호를 입력하세요.");
            return Page();
        }

        try
        {
            var existingUser = await _workspaceRepository.GetAccountByUsernameAsync(Input.Username);
            if (existingUser != null)
            {
                ModelState.AddModelError(string.Empty, "이미 존재하는 사용자명입니다.");
                return Page();
            }

            var hashedPassword = BCrypt.Net.BCrypt.EnhancedHashPassword(Input.Password);
            var newAccount = new WorkspaceAccount
            {
                Username = Input.Username.Trim(),
                PasswordHash = hashedPassword,
                Role = Input.Input?.Role ?? "Admin",
                IsActive = Input.IsActive ? "true" : "false",
                CreatedAt = DateTime.UtcNow.ToString("O"),
                UpdatedAt = DateTime.UtcNow.ToString("O")
            };

            await _workspaceRepository.UpsertAccountAsync(newAccount);
            _logger.LogInformation("[Users] New user created: {Username}", Input.Username);

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

public class CreateUserInput
{
    [Required(ErrorMessage = "사용자명을 입력하세요.")]
    [StringLength(50)]
    public string Username { get; set; } = string.Empty;

    [Required(ErrorMessage = "비밀번호를 입력하세요.")]
    [StringLength(100, MinimumLength = 8, ErrorMessage = "비밀번호는 최소 8자 이상이어야 합니다.")]
    public string Password { get; set; } = string.Empty;

    public CreateUserInput? Input { get; set; }
    public string Role { get; set; } = "Admin";
    public bool IsActive { get; set; } = true;
}
