<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPurchaseReturns\Pages;

use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Business\Purchase\PurchaseReturnService;
use App\Filament\Resources\DberpPurchaseReturns\DberpPurchaseReturnResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Filament\Support\DberpPrintFilamentAction;
use App\Models\DberpPurchaseReturnOrder;
use App\Support\DberpFilamentInventoryConfirmActionFeedback;
use App\Support\DberpFilamentInventoryVoidActionConfigurator;
use App\Support\Print\Documents\PurchaseReturnPrintPresenter;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;

class EditDberpPurchaseReturn extends EditRecord
{
    protected static string $resource = DberpPurchaseReturnResource::class;

    protected function getHeaderActions(): array
    {
        return [
            DberpPrintFilamentAction::forDocument(
                PurchaseReturnPrintPresenter::DOCUMENT_KEY,
                fn (DberpPurchaseReturnOrder $record): bool => DberpPurchaseReturnResource::canView($record),
            ),
            Action::make('apply')
                ->label(__('dberp.actions.confirm_take_effect'))
                ->requiresConfirmation()
                ->modalDescription(__('dberp.hints.inventory_apply_outbound'))
                ->visible(fn (DberpPurchaseReturnOrder $record): bool => $record->status === InventoryDocumentStatus::Draft->value)
                ->action(function (): void {
                    DberpFilamentInventoryConfirmActionFeedback::runWithFailureNotification(function (): void {
                        app(PurchaseReturnService::class)->apply($this->record);
                    });
                    $this->record->refresh();
                }),
            DberpFilamentInventoryVoidActionConfigurator::configureEffectiveInventoryVoidAction(
                Action::make('void')
                    ->requiresConfirmation()
                    ->visible(fn (DberpPurchaseReturnOrder $record): bool => $record->status === InventoryDocumentStatus::Effective->value)
                    ->action(function (): void {
                        DberpFilamentInventoryConfirmActionFeedback::runWithFailureNotification(function (): void {
                            app(PurchaseReturnService::class)->void($this->record);
                        });
                        $this->record->refresh();
                        DberpFilamentInventoryVoidActionConfigurator::notifyInventoryRevokeSuccess();
                    }),
            ),
            DeleteAction::make()
                ->visible(fn (DberpPurchaseReturnOrder $record): bool => $record->status === InventoryDocumentStatus::Draft->value),
        ];
    }
}
