<?php

declare(strict_types=1);

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

namespace App\Filament\Support;

use App\Business\Product\ProductSpecMatrixRebuildService;
use App\Models\DberpProduct;
use Closure;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Illuminate\Validation\ValidationException;

final class DberpProductSpecMatrixRebuildAction
{
    public static function make(Closure $resolveProduct, ?Closure $afterSuccess = null): Action
    {
        return Action::make('rebuildSpecMatrix')
            ->label(__('dberp.actions.rebuild_spec_matrix'))
            ->color('danger')
            ->icon('heroicon-o-arrow-path')
            ->visible(function () use ($resolveProduct): bool {
                $product = $resolveProduct();

                return $product instanceof DberpProduct
                    && app(ProductSpecMatrixRebuildService::class)->shouldOfferRebuild($product);
            })
            ->requiresConfirmation()
            ->modalHeading(__('dberp.headings.rebuild_spec_matrix'))
            ->modalDescription(__('dberp.hints.rebuild_spec_matrix'))
            ->modalSubmitActionLabel(__('dberp.actions.confirm_rebuild_spec_matrix'))
            ->action(function () use ($resolveProduct, $afterSuccess): void {
                $product = $resolveProduct();
                if (! $product instanceof DberpProduct) {
                    return;
                }

                try {
                    app(ProductSpecMatrixRebuildService::class)->rebuild($product->fresh());

                    Notification::make()
                        ->title((string) __('dberp.notifications.spec_matrix_rebuilt'))
                        ->body((string) __('dberp.messages.spec_matrix_rebuilt_next_steps'))
                        ->success()
                        ->send();

                    if ($afterSuccess !== null) {
                        $afterSuccess();
                    }
                } catch (ValidationException $exception) {
                    Notification::make()
                        ->title((string) __('dberp.notifications.operation_blocked'))
                        ->body(collect($exception->errors())->flatten()->first())
                        ->danger()
                        ->send();

                    throw $exception;
                }
            });
    }
}
