<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\QuestionBankService;

class CleanupPapers extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'exams:cleanup {--check : 检查数据完整性} {--cleanup : 清理不一致的试卷} {--fix : 修复题目数量统计}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检查和清理试卷数据完整性问题';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $questionBankService = app(QuestionBankService::class);

        if ($this->option('check')) {
            return $this->checkDataIntegrity($questionBankService);
        }

        if ($this->option('cleanup')) {
            return $this->cleanupInconsistentPapers($questionBankService);
        }

        if ($this->option('fix')) {
            return $this->fixPaperQuestionCounts($questionBankService);
        }

        // 默认执行所有操作
        $this->info('开始执行试卷数据完整性检查和清理...');

        $this->checkDataIntegrity($questionBankService);
        $this->cleanupInconsistentPapers($questionBankService);
        $this->fixPaperQuestionCounts($questionBankService);

        $this->info('所有操作完成！');
        return Command::SUCCESS;
    }

    private function checkDataIntegrity(QuestionBankService $service): int
    {
        $this->info('检查数据完整性...');

        $result = $service->checkDataIntegrity();
        $count = $result['inconsistent_count'];

        if ($count === 0) {
            $this->info('✅ 未发现数据不一致问题');
        } else {
            $this->warn("⚠️  发现 {$count} 个数据不一致的试卷：");

            $this->table(
                ['试卷ID', '试卷名称', '预期题目数', '学生ID'],
                array_map(function($paper) {
                    return [
                        $paper->paper_id,
                        $paper->paper_name ?? '未命名',
                        $paper->question_count ?? 0,
                        $paper->student_id ?? 'unknown'
                    ];
                }, $result['papers'])
            );
        }

        return $count;
    }

    private function cleanupInconsistentPapers(QuestionBankService $service): int
    {
        $this->info('清理不一致的试卷记录...');

        $deletedCount = $service->cleanupInconsistentPapers();

        if ($deletedCount === 0) {
            $this->info('✅ 没有需要清理的试卷');
        } else {
            $this->info("🗑️  已清理 {$deletedCount} 个不一致的试卷记录");
        }

        return $deletedCount;
    }

    private function fixPaperQuestionCounts(QuestionBankService $service): int
    {
        $this->info('修复试卷题目数量统计...');

        $fixedCount = $service->fixPaperQuestionCounts();

        if ($fixedCount === 0) {
            $this->info('✅ 所有试卷的题目数量统计都正确');
        } else {
            $this->info("🔧 已修复 {$fixedCount} 个试卷的题目数量统计");
        }

        return $fixedCount;
    }
}
