<?php

namespace App\Filament\Actions;

use App\Models\SopTemplate;
use App\Models\SopTemplateVersion;
use Filament\Actions\Action;
use Filament\Forms;
use Filament\Notifications\Notification;

class PublishSopTemplateAction extends Action
{
    public static function getDefaultName(): ?string
    {
        return 'publish';
    }

    protected function setUp(): void
    {
        parent::setUp();

        $this->label('发布模板');

        $this->icon('heroicon-o-check-circle');

        $this->color('success');

        $this->requiresConfirmation();

        $this->modalHeading('发布 SOP 模板');

        $this->modalDescription('发布后，模板将对所有用户可见。确定要发布吗？');

        $this->modalSubmitActionLabel('确认发布');

        $this->form([
            Forms\Components\Textarea::make('change_log')
                ->label('变更说明')
                ->placeholder('请描述本次发布的主要变更内容...')
                ->rows(3),
        ]);

        $this->visible(function ($record) {
            return $record instanceof SopTemplate && $record->status === 'draft';
        });

        $this->action(function (SopTemplate $record, array $data) {
            // 验证模板是否有步骤
            if ($record->steps()->count() === 0) {
                Notification::make()
                    ->title('发布失败')
                    ->body('模板至少需要包含一个步骤才能发布')
                    ->danger()
                    ->send();

                return;
            }

            // 创建版本快照
            SopTemplateVersion::create([
                'sop_template_id' => $record->id,
                'version' => $record->version,
                'change_log' => $data['change_log'] ?? '首次发布',
                'content_snapshot' => [
                    'template' => $record->toArray(),
                    'steps' => $record->steps->toArray(),
                ],
                'created_by' => auth()->id(),
                'created_at' => now(),
            ]);

            // 更新模板状态
            $record->update([
                'status' => 'published',
                'published_at' => now(),
            ]);

            Notification::make()
                ->title('发布成功')
                ->body('SOP 模板已成功发布')
                ->success()
                ->send();
        });
    }
}
