using FastEndpoints;
using Microsoft.AspNetCore.Authorization;
using QuantEngine.Web.Services;

namespace QuantEngine.Web.Endpoints;

public class AuthLoginRequest
{
    public string Username { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty;
}

public class AuthLoginResponse
{
    public bool Success { get; set; }
    public string Message { get; set; } = string.Empty;
    public string Username { get; set; } = string.Empty;
    public string Role { get; set; } = string.Empty;
    public string RedirectUrl { get; set; } = "/dashboard";
}

[HttpPost("/api/auth/login")]
[AllowAnonymous]
public class AuthLoginEndpoint : Endpoint<AuthLoginRequest, AuthLoginResponse>
{
    private readonly AuthService _authService;

    public AuthLoginEndpoint(AuthService authService)
    {
        _authService = authService;
    }

    public override async Task HandleAsync(AuthLoginRequest req, CancellationToken ct)
    {
        var httpContext = HttpContext;
        var ipAddress = httpContext.Connection.RemoteIpAddress?.ToString() ?? "127.0.0.1";

        var account = await _authService.AuthenticateAsync(req.Username, req.Password, ipAddress);
        if (account is null)
        {
            await SendAsync(new AuthLoginResponse
            {
                Success = false,
                Message = "아이디 또는 비밀번호가 올바르지 않거나 잠긴 계정입니다."
            }, 401, ct);
            return;
        }

        await SendAsync(new AuthLoginResponse
        {
            Success = true,
            Message = "로그인 성공",
            Username = account.Username,
            Role = account.Role,
            RedirectUrl = "/dashboard"
        }, 200, ct);
    }
}
