<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use App\Services\Billing\PaymentService;

/**
 * No 'auth' filter on this route group — gateways call this directly,
 * unauthenticated by bearer token. Trust is established purely via
 * PaymentService::handleWebhook()'s signature verification inside each
 * gateway adapter (see 09-security-plan.md §8).
 */
class WebhookController extends BaseController
{
    public function handle(string $gateway)
    {
        $rawPayload = $this->request->getBody();
        $headers = [];
        foreach ($this->request->headers() as $header) {
            $headers[$header->getName()] = $header->getValueLine();
        }

        $service = new PaymentService();
        $result = $service->handleWebhook($gateway, $rawPayload, $headers);

        // Always 200 on a well-formed-but-rejected webhook so the gateway
        // doesn't endlessly retry a payload that will never verify; log
        // the rejection reason for investigation instead of surfacing an
        // error status that triggers gateway retry storms.
        if (! $result['handled']) {
            log_message('warning', "Webhook rejected for gateway {$gateway}: " . ($result['reason'] ?? 'unknown'));
        }

        return $this->response->setStatusCode(200)->setJSON(['received' => true]);
    }
}
