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

namespace Csob.Controllers;

/// <summary>
/// PISP – direct-debit mandate initiation and its authorization (sign) flow. Requires the ČSOB
/// credential headers. The mandate body is forwarded to ČSOB as raw JSON (COBS direct-debit shape).
/// </summary>
[ApiController]
[Route("direct-debits")]
[Produces("application/json")]
[Tags("PISP – Direct debits")]
public sealed class DirectDebitsController : ControllerBase
{
    private readonly DirectDebitsService _service;

    public DirectDebitsController(DirectDebitsService service) => _service = service;

    /// <summary>Initiate a direct-debit mandate.</summary>
    [HttpPost]
    public async Task<IActionResult> Initiate([FromBody] JsonNode request, CancellationToken ct)
        => Ok(await _service.InitiateAsync(request, ct));

    /// <summary>Get the direct-debit mandate detail.</summary>
    [HttpGet("{id}")]
    public async Task<IActionResult> Detail(string id, CancellationToken ct)
        => Ok(await _service.DetailAsync(id, ct));

    /// <summary>Get the direct-debit instruction status.</summary>
    [HttpGet("{id}/status")]
    public async Task<IActionResult> Status(string id, CancellationToken ct)
        => Ok(await _service.StatusAsync(id, ct));

    /// <summary>Revoke a direct-debit mandate.</summary>
    [HttpDelete("{id}")]
    public async Task<IActionResult> Cancel(string id, CancellationToken ct)
        => Ok(await _service.CancelAsync(id, ct));

    /// <summary>Start the authorization (SCA) of a direct-debit mandate. Returns the PSU redirect details.</summary>
    [HttpPost("{id}/sign/{signId}")]
    public async Task<IActionResult> StartSign(string id, string signId, [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] JsonNode? body, CancellationToken ct)
        => Ok(await _service.StartSignAsync(id, signId, body, ct));

    /// <summary>Get the current state of an authorization (sign) transaction.</summary>
    [HttpGet("{id}/sign/{signId}")]
    public async Task<IActionResult> SignStatus(string id, string signId, CancellationToken ct)
        => Ok(await _service.SignStatusAsync(id, signId, ct));

    /// <summary>Finalize an authorization (sign) transaction.</summary>
    [HttpPut("{id}/sign/{signId}")]
    public async Task<IActionResult> FinalizeSign(string id, string signId, [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] JsonNode? body, CancellationToken ct)
        => Ok(await _service.FinalizeSignAsync(id, signId, body, ct));
}
