<?php

namespace App\Filament\Resources\SourcePaperResource\Actions;

use App\Jobs\PromoteSourcePapersJob;
use App\Services\TaskManager;
use Filament\Actions\BulkAction;
use Filament\Notifications\Notification;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Log;

class GenerateQuestionsBulkAction extends BulkAction
{
    public function getName(): string
    {
        return 'generate_questions';
    }

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

        $this->label('一键生成题库');
        $this->color('primary');
        $this->icon('heroicon-o-sparkles');
        $this->requiresConfirmation();
        $this->modalHeading('一键生成题库');
        $this->modalDescription('将选中的源卷子下已校对题目入库到题库，并上传图片到春笋云。');

        $this->action(function (Collection $records) {
            $this->generateQuestions($records);
        });
    }

    private function generateQuestions(Collection $records): void
    {
        try {
            $paperIds = $records->pluck('id')->map(fn ($id) => (int) $id)->all();
            if (empty($paperIds)) {
                Notification::make()
                    ->title('未选择任何卷子')
                    ->warning()
                    ->send();
                return;
            }

            $taskId = app(TaskManager::class)->createTask(
                TaskManager::TASK_TYPE_ANALYSIS,
                ['type' => 'source_paper_import', 'paper_ids' => $paperIds]
            );
            PromoteSourcePapersJob::dispatch($taskId, $paperIds);

            Notification::make()
                ->title("已加入队列，任务号：{$taskId}")
                ->success()
                ->send();
        } catch (\Throwable $e) {
            Log::error('Generate questions bulk action failed', [
                'error' => $e->getMessage(),
            ]);

            Notification::make()
                ->title('入库失败：' . $e->getMessage())
                ->danger()
                ->send();
        }
    }
}
