using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nexus.Contracts.Auth;
using NexusIdentity.Api.Services;

namespace NexusIdentity.Api.Controllers;

[ApiController]
public sealed class TokenController : ControllerBase
{
    private readonly TokenService _tokenService;

    public TokenController(TokenService tokenService)
    {
        _tokenService = tokenService;
    }

    [AllowAnonymous]
    [HttpPost("connect/token")]
    [Consumes("application/x-www-form-urlencoded")]
    public async Task<IActionResult> ConnectToken(
        [FromForm(Name = "grant_type")] string grantType,
        [FromForm(Name = "client_id")] string clientId,
        [FromForm(Name = "username")] string? username,
        [FromForm(Name = "password")] string? password,
        [FromForm(Name = "refresh_token")] string? refreshToken,
        CancellationToken ct)
    {
        if (!string.Equals(clientId, "nexus-shell", StringComparison.Ordinal))
        {
            return BadRequest(new { error = "invalid_client" });
        }

        TokenResponse? tokens = grantType switch
        {
            "password" when !string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password)
                => await _tokenService.IssuePasswordGrantAsync(username, password, ct),
            "refresh_token" when !string.IsNullOrWhiteSpace(refreshToken)
                => await _tokenService.IssueRefreshGrantAsync(refreshToken, ct),
            _ => null,
        };

        if (tokens is null)
        {
            return Unauthorized(new { error = "invalid_grant" });
        }

        return Ok(tokens);
    }
}
