<?php

namespace Modules\Payment\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Gate;
use Modules\Booking\Models\Booking;
use Modules\Payment\Actions\RefundBookingAction;
use Modules\Payment\Http\Requests\RefundBookingRequest;
use Modules\Payment\Http\Resources\RefundResource;

class RefundController extends Controller
{
    public function __construct(
        private RefundBookingAction $refundBookingAction,
    ) {}

    public function refund(RefundBookingRequest $request, Booking $booking): JsonResponse
    {
        $validated = $request->validated();

        $openid = $request->attributes->get('fastapi_openid');

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

        $refund = $this->refundBookingAction->handle(
            $booking,
            (string) $validated['amount'],
            $validated['reason'],
            $request->user()?->id,
        );

        return (new RefundResource($refund))
            ->response()
            ->setStatusCode(201);
    }
}
