using DoliMiddlewareApi.Services.Notifications;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DoliMiddlewareApi.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class SettingsController(
    WebhookSettings webhookSettings,
    INotificationService notifications) : ControllerBase
{
    [HttpGet("webhook")]
    [ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
    public IActionResult GetWebhook()
    {
        return Ok(new { url = webhookSettings.WebhookUrl });
    }

    [HttpPut("webhook")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public IActionResult SetWebhook([FromBody] SetWebhookDto dto)
    {
        webhookSettings.UpdateUrl(dto.Url);
        return NoContent();
    }

    [HttpPost("webhook/test")]
    [ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> TestWebhook()
    {
        if (string.IsNullOrWhiteSpace(webhookSettings.WebhookUrl))
            return BadRequest(new { error = "No hay webhook configurado." });

        await notifications.NotifyInvoiceStatusChangedAsync(0, "TEST-0001", "paid");
        return Ok(new { message = "Notificación de prueba enviada.", url = webhookSettings.WebhookUrl });
    }
}

public class SetWebhookDto
{
    public string? Url { get; set; }
}
