<?php

namespace App\Http\Controllers;

use App\Services\FinalizeOrderPaymentService;
use App\Services\StripeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class StripeWebhookController extends Controller
{
    public function __construct(
        protected StripeService $stripeService,
        protected FinalizeOrderPaymentService $finalizeOrderPayment
    ) {}

    public function handle(Request $request)
    {
        $payload = $request->getContent();
        $sig = $request->header('Stripe-Signature', '');

        try {
            $event = $this->stripeService->constructWebhookEvent($payload, $sig);
        } catch (\Exception $e) {
            Log::warning('Stripe webhook signature verification failed: '.$e->getMessage());

            return response()->json(['error' => $e->getMessage()], 400);
        }

        if ($event === null) {
            Log::warning('Stripe webhook : secret webhook non configuré (STRIPE_WEBHOOK_SECRET / réglages).');

            return response()->json(['error' => 'Webhook non configuré'], 503);
        }

        if ($event->type === 'payment_intent.succeeded') {
            $this->finalizeOrderPayment->finalizeFromWebhookPaymentIntent($event->data->object);
        }

        return response()->json(['received' => true]);
    }

}
