<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Link;
use App\Models\Payment;
use App\Enums\LinkStatus;
use App\Enums\PaymentStatus;
use Illuminate\Support\Facades\Log;

class WebhookController extends Controller
{
    public function handle(Request $request)
    {
        // 1. Vérifier la signature
        $signature = $request->header('X-Feda-Signature');
        $payload = $request->getContent();
        $secret  = config('services.fedapay.secret');
        if (!hash_equals(hash_hmac('sha256', $payload, $secret), $signature)) {
            Log::warning('FedaPay signature mismatch', ['payload'=>$payload]);
            return response()->json(['message'=>'Invalid signature'], 400);
        }

        // 2. Traiter le webhook
        $data = $request->json()->all();
        $fedaRequestId = $data['request_id'] ?? null;
        $fedaPaymentId = $data['id'] ?? null;
        $status        = $data['status'] ?? null;

        if (!$fedaRequestId || !$fedaPaymentId) {
            Log::error('FedaPay webhook missing data', $data);
            return response()->json(['message'=>'Missing data'], 400);
        }

        // 3. Mettre à jour link et payments
        $link = Link::where('feda_request_id', $fedaRequestId)->first();
        if (!$link) {
            Log::error('Link not found for FedaPay request', ['request_id'=>$fedaRequestId]);
            return response()->json(['message'=>'Link not found'], 404);
        }

        // Créer ou mettre à jour la payment
        $payment = Payment::updateOrCreate(
            ['feda_payment_id' => $fedaPaymentId],
            [
                'link_id'  => $link->id,
                'amount'   => (int) round($data['amount'] / 100), // convertir cents en XOF
                'currency' => $data['currency'],
                'status'   => PaymentStatus::from($status),
                'paid_at'  => $data['paid_at'] ?? now(),
            ]
        );

        // Mettre à jour le status du link
        if ($status === PaymentStatus::Paid->value) {
            $link->update(['status' => LinkStatus::Paid]);
        }

        return response()->json(['message'=>'Success'], 200);
    }
}
