<?php

namespace Modules\Booking\Filament\Resources\Bookings\Actions;

use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Gate;
use Modules\Booking\Actions\CancelBookingAction;
use Modules\Booking\Enums\BookingStatus;
use Modules\Booking\Exceptions\BookingCannotBeCancelledException;
use Modules\Booking\Models\Booking;

/**
 * Shared between BookingsTable (row action) and ViewBooking (header action)
 * so both surfaces stay in sync — one definition, not two.
 */
class CancelBookingTableAction
{
    public static function make(): Action
    {
        return Action::make('cancel')
            ->label('Cancel')
            ->icon(Heroicon::OutlinedXCircle)
            ->color('danger')
            ->requiresConfirmation()
            ->visible(fn (Booking $record): bool => Gate::allows('cancel', $record))
            ->disabled(fn (Booking $record): bool => $record->status !== BookingStatus::PendingPayment)
            ->action(function (Booking $record, CancelBookingAction $cancelBookingAction) {
                try {
                    $cancelBookingAction->handle($record);

                    Notification::make()
                        ->title('Booking cancelled')
                        ->success()
                        ->send();
                } catch (BookingCannotBeCancelledException $exception) {
                    Notification::make()
                        ->title('Cannot cancel booking')
                        ->body($exception->getMessage())
                        ->danger()
                        ->send();
                }
            });
    }
}
