<?php

namespace App\Http\Controllers;

use App\Services\Payments\PaymentGatewayManager;
use App\Services\Payments\PaymentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use InvalidArgumentException;

/**
 * Inbound provider webhooks (PRD 19).
 *
 * Always answers 200 for a well-formed request so providers do not retry
 * endlessly; the payload is validated by signature inside PaymentService.
 */
class WebhookController extends Controller
{
    public function __construct(
        protected PaymentService $payments,
        protected PaymentGatewayManager $gateways,
    ) {}

    public function __invoke(Request $request, string $provider): JsonResponse
    {
        try {
            $this->gateways->driver($provider);
        } catch (InvalidArgumentException) {
            return response()->json(['message' => 'Unknown provider.'], 404);
        }

        $result = $this->payments->handleWebhook($provider, $request);

        return $result->valid
            ? response()->json(['received' => true])
            : response()->json(['message' => 'Invalid webhook.'], 400);
    }
}
