<?php

namespace Modules\Payment\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Gate;
use Modules\Booking\Models\Booking;
use Modules\Payment\Actions\InitiatePaymentAction;
use Modules\Payment\Enums\PaymentStatus;
use Modules\Payment\Http\Resources\PaymentResource;

class PaymentController extends Controller
{
    public function __construct(
        private InitiatePaymentAction $initiatePaymentAction,
    ) {}

    public function initiate(Request $request, Booking $booking): JsonResponse
    {
        $openid = $request->attributes->get('fastapi_openid');

        if ($openid === null) {
            Gate::authorize('pay', $booking);
        }

        $payment = $this->initiatePaymentAction->handle($booking);

        if ($payment->status === PaymentStatus::Failed) {
            return response()->json([
                'message' => 'Payment initiation failed',
                'errors' => [
                    'payment' => ['Payment initiation failed'],
                ],
            ], 422);
        }

        return (new PaymentResource($payment))
            ->response()
            ->setStatusCode(201);
    }
}
