<?php

namespace App\Jobs;

use App\Models\SourcePaper;
use App\Services\QuestionCandidateToQuestionService;
use App\Services\TaskManager;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class PromoteSourcePapersJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function __construct(
        public readonly string $taskId,
        public readonly array $paperIds
    ) {}

    public function handle(TaskManager $taskManager, QuestionCandidateToQuestionService $service): void
    {
        $paperIds = array_values(array_filter(array_unique(array_map('intval', $this->paperIds))));
        if (empty($paperIds)) {
            $taskManager->markTaskFailed($this->taskId, '未选择任何卷子');
            return;
        }

        $papers = SourcePaper::query()->whereIn('id', $paperIds)->get();
        if ($papers->isEmpty()) {
            $taskManager->markTaskFailed($this->taskId, '未找到可入库的卷子');
            return;
        }

        $summary = [
            'processed' => 0,
            'skipped' => 0,
            'errors' => 0,
        ];

        $total = $papers->count();
        $taskManager->updateTaskProgress($this->taskId, 5, '开始入库');

        foreach ($papers as $index => $paper) {
            $taskManager->updateTaskProgress(
                $this->taskId,
                (int) (5 + (($index / max(1, $total)) * 80)),
                '正在处理：' . ($paper->title ?: ('卷子 #' . $paper->id))
            );

            $result = $service->promoteFromSourcePapers(collect([$paper]));
            $summary['processed'] += $result['processed'];
            $summary['skipped'] += $result['skipped'];
            $summary['errors'] += $result['errors'];
        }

        $taskManager->markTaskCompleted($this->taskId, [
            'processed' => $summary['processed'],
            'skipped' => $summary['skipped'],
            'errors' => $summary['errors'],
        ]);

        Log::info('PromoteSourcePapersJob completed', [
            'task_id' => $this->taskId,
            'paper_ids' => $paperIds,
            'summary' => $summary,
        ]);
    }
}
