<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpProducts\Pages;

use App\Filament\Resources\DberpProducts\DberpProductResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Filament\Support\DberpProductSpecMatrixRebuildAction;
use App\Models\DberpProduct;
use App\Support\PluginIntegration\BarcodeLabelFilamentBridge;
use App\Support\PluginIntegration\DberpAiPageContextFilamentBridge;
use App\Tools\Context\PageKind;
use Filament\Actions\DeleteAction;
use Filament\Actions\ViewAction;

class EditDberpProduct extends EditRecord
{
    protected static string $resource = DberpProductResource::class;

    private bool $specEnabledChanged = false;

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeSave(array $data): array
    {
        $record = $this->getRecord();
        if ($record instanceof DberpProduct) {
            $this->specEnabledChanged = (bool) ($data['spec_enabled'] ?? false) !== (bool) $record->spec_enabled;
        }

        return $data;
    }

    protected function afterSave(): void
    {
        if (! $this->specEnabledChanged) {
            return;
        }

        $record = $this->getRecord();
        if (! $record instanceof DberpProduct) {
            return;
        }

        $this->redirect($this->getResource()::getUrl('edit', ['record' => $record]));
    }

    protected function getHeaderActions(): array
    {
        return [
            ...DberpAiPageContextFilamentBridge::recordHeaderActionsFor(
                $this->getRecord(),
                PageKind::ProductEdit,
            ),
            ...BarcodeLabelFilamentBridge::productHeaderActions(
                fn (): ?DberpProduct => $this->getRecord() instanceof DberpProduct ? $this->getRecord() : null,
            ),
            ViewAction::make(),
            DberpProductSpecMatrixRebuildAction::make(
                fn (): ?DberpProduct => $this->getRecord() instanceof DberpProduct ? $this->getRecord() : null,
                fn (): mixed => $this->redirect($this->getResource()::getUrl('edit', ['record' => $this->getRecord()])),
            ),
            DeleteAction::make(),
        ];
    }
}
