using ERPCore.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace ERPCore.Controllers;

/// <summary>
/// Generic reverse proxy into the external General Ledger service — forwards every
/// method/path/query/body under this prefix verbatim via
/// <see cref="IGeneralLedgerService"/> and returns GL's response (status, content-type,
/// body) unchanged. No endpoint-specific shape lives here; see
/// docs/12-GENERAL-LEDGER-INTEGRATION.md for the full GL contract and what this proxy
/// does and doesn't do. Gated by the same ERP door policy as every other v1 endpoint
/// (<see cref="ApiControllerBase"/>) — the shared GL API key is attached server-side
/// only and is never exposed to the frontend.
/// </summary>
[Route("api/v1/gl")]
public sealed class GeneralLedgerController : ApiControllerBase
{
    private readonly IGeneralLedgerService _gl;

    public GeneralLedgerController(IGeneralLedgerService gl) => _gl = gl;

    [HttpGet("{**path}")]
    public Task<IActionResult> Get(string path, CancellationToken ct) => ForwardAsync(HttpMethod.Get, path, ct);

    [HttpPost("{**path}")]
    public Task<IActionResult> Post(string path, CancellationToken ct) => ForwardAsync(HttpMethod.Post, path, ct);

    [HttpPut("{**path}")]
    public Task<IActionResult> Put(string path, CancellationToken ct) => ForwardAsync(HttpMethod.Put, path, ct);

    private async Task<IActionResult> ForwardAsync(HttpMethod method, string path, CancellationToken ct)
    {
        var body = method == HttpMethod.Get ? null : Request.Body;
        var result = await _gl.ForwardAsync(method, path, Request.QueryString.Value, Request.ContentType, body, ct);
        return new ContentResult
        {
            StatusCode = result.StatusCode,
            Content = result.Body,
            ContentType = result.ContentType ?? "application/json"
        };
    }
}
