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

namespace Meezi.API.Controllers;

[ApiController]
[AllowAnonymous]
[Route("api/webhooks/digikala")]
public class DigikalaWebhookController : ControllerBase
{
    private readonly IDeliveryWebhookIngressService _ingress;
    private readonly DeliveryPlatformsOptions _options;

    public DigikalaWebhookController(
        IDeliveryWebhookIngressService ingress,
        IOptions<DeliveryPlatformsOptions> options)
    {
        _ingress = ingress;
        _options = options.Value;
    }

    [HttpPost]
    public async Task<IActionResult> Receive(CancellationToken ct)
    {
        if (!_options.Digikala.Enabled)
            return NotFound(new ApiResponse<object>(false, null, new ApiError("NOT_FOUND", "Digikala webhook disabled.")));

        using var reader = new StreamReader(Request.Body);
        var rawBody = await reader.ReadToEndAsync(ct);

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

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