<?php

declare(strict_types=1);

require_once __DIR__ . '/../../models/WhatsAppConfig.php';
require_once __DIR__ . '/../../models/WhatsAppLog.php';
require_once __DIR__ . '/../../models/WhatsAppDispatch.php';
require_once __DIR__ . '/../../services/WhatsAppService.php';

class ApiWhatsAppController extends Controller
{
    public function webhook(): void
    {
        $service = new WhatsAppService();
        $token = $_SERVER['HTTP_X_WEBHOOK_TOKEN'] ?? Request::bearerToken();

        if (!$service->webhookTokenMatches(is_string($token) ? $token : null)) {
            ApiAuth::requireToken();
        }

        $payload = Request::json();
        $result = $service->handleWebhook($payload);

        if (!empty($result['success'])) {
            ApiResponse::success($result['data'] ?? null, $result['message'] ?? 'Webhook processado.');
        }

        ApiResponse::error($result['message'] ?? 'Falha ao processar webhook.', $result['data'] ?? [], 422);
    }

    public function runSla(): void
    {
        ApiAuth::requireToken();
        $service = new WhatsAppService();
        $result = $service->processSlaAlerts();
        ApiResponse::success($result, 'Automação de SLA processada.');
    }
}
