<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPurchaseExceptions\Pages;

use App\Business\Purchase\Enums\PurchaseExceptionResolutionResult;
use App\Business\Purchase\Enums\PurchaseExceptionStatus;
use App\Business\Purchase\PurchaseExceptionService;
use App\Filament\Resources\DberpPurchaseExceptions\DberpPurchaseExceptionResource;
use App\Models\DberpPurchaseException;
use Filament\Actions\Action;
use App\Filament\Resources\Pages\EditRecord;

class EditDberpPurchaseException extends EditRecord
{
    protected static string $resource = DberpPurchaseExceptionResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Action::make('submit_resolution')
                ->label(__('dberp.actions.submit_resolution'))
                ->requiresConfirmation()
                ->visible(fn (DberpPurchaseException $record): bool => in_array($record->status, [PurchaseExceptionStatus::Pending->value, PurchaseExceptionStatus::Processing->value], true))
                ->action(function (): void {
                    $result = PurchaseExceptionResolutionResult::from((string) ($this->data['resolution_result'] ?? PurchaseExceptionResolutionResult::FollowUp->value));
                    app(PurchaseExceptionService::class)->submitResolution($this->record, $result, (string) ($this->data['resolution_remark'] ?? ''));
                    $this->record->refresh();
                }),
            Action::make('close_exception')
                ->label(__('dberp.actions.close_exception'))
                ->requiresConfirmation()
                ->visible(fn (DberpPurchaseException $record): bool => $record->status !== PurchaseExceptionStatus::Closed->value)
                ->action(function (): void {
                    app(PurchaseExceptionService::class)->close($this->record, (string) ($this->data['resolution_remark'] ?? ''));
                    $this->record->refresh();
                }),
            Action::make('reopen')
                ->label(__('dberp.actions.reopen'))
                ->requiresConfirmation()
                ->visible(fn (DberpPurchaseException $record): bool => $record->status !== PurchaseExceptionStatus::Pending->value)
                ->action(function (): void {
                    app(PurchaseExceptionService::class)->reopen($this->record, (string) ($this->data['resolution_remark'] ?? ''));
                    $this->record->refresh();
                }),
        ];
    }
}