<?php

declare(strict_types=1);

namespace Plugins\Larablog\Payment\Filament\Resources\OrderResource\Pages;

use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Plugins\Larablog\Payment\Domain\OrderService;
use Plugins\Larablog\Payment\Filament\Resources\OrderResource;
use Plugins\Larablog\Payment\Models\Order;
use Throwable;

class ViewOrder extends ViewRecord
{
    protected static string $resource = OrderResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Action::make('markPaid')
                ->label(__('admin.actions.mark_paid'))
                ->icon('heroicon-o-check-circle')
                ->color('success')
                ->requiresConfirmation()
                ->visible(fn (): bool => $this->getRecord() instanceof Order && $this->getRecord()->isPending())
                ->action(function (OrderService $orders): void {
                    /** @var Order $order */
                    $order = $this->getRecord();

                    try {
                        $orders->markPaid($order, [
                            'source' => 'admin',
                            'marked_by' => auth()->id(),
                        ]);
                    } catch (Throwable $e) {
                        Notification::make()
                            ->title(__('admin.messages.mark_paid_failed'))
                            ->body($e->getMessage())
                            ->danger()
                            ->send();

                        return;
                    }

                    $this->record->refresh();
                    $this->record->loadMissing('user');

                    Notification::make()
                        ->title(__('admin.messages.mark_paid_success'))
                        ->success()
                        ->send();
                }),
        ];
    }
}
