<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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();
                }),
        ];
    }
}