<?php

declare(strict_types=1);

namespace App\Http\Controllers\Wallet;

use App\Http\Controllers\Controller;
use App\Http\Requests\Wallet\WalletDepositRequest;
use App\Http\Resources\PaymentResource;
use App\Models\Charge;
use App\Models\Payment;
use App\Services\PaymentService;
use App\Support\ApiResponse;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;

class WalletDepositController extends Controller
{
    public function __invoke(WalletDepositRequest $request, PaymentService $paymentService)
    {
        Gate::authorize('create', Payment::class);

        $user = Auth::user();
        $amount = $request->integer('price');
        $gateway = (string) $request->input('gateway', config('payment.default', 'zibal'));

        try {
            DB::beginTransaction();

            $charge = Charge::create([
                'user_id' => $user->id,
                'amount' => $amount,
                'status' => 'pending',
            ]);

            $result = $paymentService->startGateway(
                $user,
                $amount,
                Charge::class,
                (int) $charge->id,
                $gateway,
                (string) $charge->id,
            );

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();

            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return ApiResponse::response(
            data: [
                'charge_id' => $charge->id,
                'payment' => new PaymentResource($result['payment']->loadMissing('user')),
                'gateway_url' => $result['gateway_url'],
                'gateway' => $result['gateway'],
            ],
            next: $result['gateway_url'],
            message: 'در حال انتقال به درگاه برای شارژ کیف پول.',
            status: 201,
        );
    }
}
