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/snappfood")]
public class SnappfoodWebhookController : ControllerBase
{
    private readonly IDeliveryWebhookIngressService _ingress;

    public SnappfoodWebhookController(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-Snappfood-Signature"].FirstOrDefault()
            ?? Request.Headers["X-Hub-Signature-256"].FirstOrDefault();

        var result = await _ingress.ReceiveAsync(DeliveryPlatform.Snappfood, 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 }));
    }
}
