using MemberCenter.Api.Contracts;
using MemberCenter.Application.Abstractions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OpenIddict.Abstractions;

namespace MemberCenter.Api.Controllers;

[ApiController]
[Route("integrations/send-engine")]
public class SendEngineIntegrationController : ControllerBase
{
    private readonly ITenantService _tenantService;

    public SendEngineIntegrationController(ITenantService tenantService)
    {
        _tenantService = tenantService;
    }

    [Authorize]
    [HttpPost("webhook-clients/upsert")]
    public async Task<IActionResult> UpsertWebhookClient([FromBody] UpsertSendEngineWebhookClientRequest request)
    {
        if (!HasScope(User, "newsletter:events.write.global"))
        {
            return Forbid();
        }

        if (request.TenantId == Guid.Empty || request.WebhookClientId == Guid.Empty)
        {
            return BadRequest("tenant_id and webhook_client_id are required.");
        }

        var updated = await _tenantService.SetSendEngineWebhookClientAsync(request.TenantId, request.WebhookClientId);
        if (!updated)
        {
            return NotFound("Tenant not found.");
        }

        return Ok(new
        {
            tenant_id = request.TenantId,
            webhook_client_id = request.WebhookClientId,
            status = "updated"
        });
    }

    private static bool HasScope(System.Security.Claims.ClaimsPrincipal user, string scope)
    {
        var values = user.FindAll(OpenIddictConstants.Claims.Scope)
            .SelectMany(c => c.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries));
        return values.Contains(scope, StringComparer.Ordinal);
    }
}
