using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Meezi.API.Services.Delivery;
using Meezi.Core.Enums;
using Meezi.Shared;

namespace Meezi.API.Controllers;

[ApiController]
[AllowAnonymous]
[Route("api/webhooks/tap30")]
public class Tap30WebhookController : ControllerBase
{
    private readonly IDeliveryWebhookIngressService _ingress;

    public Tap30WebhookController(IDeliveryWebhookIngressService ingress) => _ingress = ingress;

    [HttpPost]
    public async Task<IActionResult> Receive(CancellationToken ct)
    {
        using var reader = new StreamReader(Request.Body);
        var rawBody = await reader.ReadToEndAsync(ct);

        var signature = Request.Headers["X-Tap30-Signature"].FirstOrDefault()
            ?? Request.Headers["X-Hub-Signature-256"].FirstOrDefault();

        var result = await _ingress.ReceiveAsync(DeliveryPlatform.Tap30, rawBody, signature, ct);
        if (!result.Accepted)
        {
            var status = result.ErrorCode == "UNAUTHORIZED"
                ? StatusCodes.Status401Unauthorized
                : StatusCodes.Status400BadRequest;
            return StatusCode(status, new ApiResponse<object>(false, null,
                new ApiError(result.ErrorCode ?? "ERROR", result.Message ?? "Failed.")));
        }

        return Ok(new ApiResponse<object>(true, new { received = true, logId = result.WebhookLogId }));
    }
}
