<?php

namespace App\Filament\Resources\TerminalResource\Pages;

use App\Filament\Resources\TerminalResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;

class EditTerminal extends EditRecord
{
    protected static string $resource = TerminalResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\ViewAction::make()
                ->label('查看'),
            Actions\DeleteAction::make()
                ->label('删除'),
        ];
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }

    protected function getSavedNotificationTitle(): ?string
    {
        return '终端更新成功';
    }

    protected function mutateFormDataBeforeFill(array $data): array
    {
        // 加载提示词数据到表单
        if ($this->record->prompt) {
            $data['prompt'] = [
                'prompt_template' => $this->record->prompt->prompt_template,
                'variables' => $this->record->prompt->variables,
            ];
        }
        
        return $data;
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // 提取提示词数据，稍后单独处理
        $this->promptData = $data['prompt'] ?? null;
        unset($data['prompt']);
        
        return $data;
    }

    protected function afterSave(): void
    {
        // 更新或创建提示词
        if (!empty($this->promptData['prompt_template'])) {
            $this->record->prompt()->updateOrCreate(
                ['terminal_id' => $this->record->id],
                [
                    'prompt_template' => $this->promptData['prompt_template'],
                    'variables' => $this->promptData['variables'] ?? [],
                ]
            );
        } elseif ($this->record->prompt) {
            // 如果提示词模板为空，删除现有提示词
            $this->record->prompt()->delete();
        }
    }

    private ?array $promptData = null;
}
