<?php

namespace App\Http\Controllers\Api\Finance;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Payments\PaypalExecuteRequest;
use App\Services\Payments\PaypalPaymentService;
use Illuminate\Http\JsonResponse;

class PaypalPaymentController extends BaseApiController
{
    public function __construct(private PaypalPaymentService $service)
    {
        parent::__construct();
    }

    public function redirect(): JsonResponse
    {
        return response()->json([
            'ok' => true,
            'redirect_url' => $this->service->getRedirectUrl(),
        ]);
    }

    public function create(int $paymentId): JsonResponse
    {
        $result = $this->service->createPayment($paymentId);

        return response()->json(['ok' => true] + $result);
    }

    public function execute(PaypalExecuteRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $this->service->executePayment(
            (string) $payload['payer_id'],
            $payload['paypal_payment_id'] ?? null
        );

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

    public function cancel(): JsonResponse
    {
        $this->service->cancelPayment();

        return response()->json([
            'ok' => true,
            'message' => 'Payment was canceled.',
        ]);
    }
}
