<?php

declare(strict_types=1);

namespace App\Http\Controllers\Payment;

use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Services\PaymentService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class VerifyPaymentController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request, Payment $payment)
    {
        $query = http_build_query($request->all());
        $frontend = rtrim((string) config('services.frontend_url', 'http://localhost:3000'), '/');

        try {
            DB::beginTransaction();

            $paymentService = new PaymentService;
            $paymentService->verify($request, $payment);

            DB::commit();

            return redirect($frontend . '/payment/' . $payment->id . '?status=success&' . $query);
        } catch (Exception $exception) {
            DB::rollBack();

            return redirect($frontend . '/payment/' . $payment->id . '?status=failed&message=' . urlencode($exception->getMessage()) . '&' . $query);
        }
    }
}
