using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Mvc;
using Csob.Models;
using Csob.Services;

namespace Csob.Controllers;

/// <summary>
/// OAuth2 Authorization Code helper for the ČSOB PSD2 PSU consent flow. Build the authorization URL,
/// redirect the PSU to it, then exchange the returned code for tokens. The token/refresh calls run
/// over mutual TLS, so they require the <c>X-CSOB-Certificate</c> header; client id/secret are also
/// supplied per request (this service is multi-tenant).
/// </summary>
[ApiController]
[Route("oauth")]
[Produces("application/json")]
[Tags("OAuth2")]
public sealed class OAuthController : ControllerBase
{
    private readonly OAuthService _service;

    public OAuthController(OAuthService service) => _service = service;

    /// <summary>Build the ČSOB authorization URL to which the PSU must be redirected.</summary>
    [HttpGet("authorization-url")]
    public IActionResult AuthorizationUrl(
        [FromQuery] string redirectUri, [FromQuery] string? scope, [FromQuery] string? state)
        => Ok(_service.BuildAuthorizationUrl(redirectUri, scope, state));

    /// <summary>Exchange an authorization code for an access/refresh token (mutual TLS).</summary>
    [HttpPost("token")]
    public async Task<ActionResult<JsonNode>> Token([FromBody] TokenExchangeRequest request, CancellationToken ct)
        => Ok(await _service.ExchangeCodeAsync(request, ct));

    /// <summary>Refresh an access token using a refresh token (mutual TLS).</summary>
    [HttpPost("refresh")]
    public async Task<ActionResult<JsonNode>> Refresh([FromBody] TokenRefreshRequest request, CancellationToken ct)
        => Ok(await _service.RefreshAsync(request, ct));
}
