<?php

namespace App\Http\Controllers\SelfPaced\Public;

use App\Http\Controllers\Controller;
use App\Services\PaystackService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * PaystackWebhookController
 *
 * Handles Paystack webhook events for payment verification.
 * Endpoint: POST /self-paced/paystack/webhook (no auth, no CSRF)
 *
 * Requirements: 1.7, 1.8, 11.1, 11.2, 11.6, 11.7, 11.8, 11.9
 */
class PaystackWebhookController extends Controller
{
    public function __construct(
        protected PaystackService $paystackService
    ) {}

    /**
     * Handle Paystack webhook event
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function handle(Request $request): JsonResponse
    {
        $signature = $request->header('x-paystack-signature');
        $payload = $request->getContent();

        // Get webhook secret from config
        $webhookSecret = config('services.paystack.webhook_secret');

        if (!$webhookSecret) {
            Log::error('Paystack webhook secret not configured');
            return response()->json(['status' => 'error'], 400);
        }

        // Verify signature
        if (!$this->paystackService->validateWebhookSignature($payload, $signature, $webhookSecret)) {
            Log::warning('Paystack webhook signature verification failed', [
                'signature' => substr($signature, 0, 20) . '...',
            ]);
            return response()->json(['status' => 'signature_failed'], 400);
        }

        // Parse event
        $event = $request->json()->all();
        $eventType = $event['event'] ?? null;
        $reference = $event['data']['reference'] ?? null;

        Log::info('Paystack webhook received', [
            'event_type' => $eventType,
            'reference' => $reference,
        ]);

        // Process charge.success events
        if ($eventType === 'charge.success') {
            try {
                app('App\Services\SelfPacedService')->handlePaystackWebhook($event);
            } catch (\Exception $e) {
                Log::error('Paystack webhook processing failed', [
                    'reference' => $reference,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        // Always return 200 for webhook success
        return response()->json(['status' => 'success'], 200);
    }
}
