<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Paper;
use App\Services\ExamPdfExportService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

class ExamAnalysisApiController extends Controller
{
    public function store(Request $request, ExamPdfExportService $pdfExportService): JsonResponse
    {
        $data = $request->validate([
            'paper_id' => 'required|string',
            'student_id' => 'nullable|string',
        ]);

        $paperId = $data['paper_id'];
        $studentId = $data['student_id'] ?? null;

        $paper = Paper::find($paperId);
        if (!$paper) {
            return response()->json([
                'success' => false,
                'message' => '未找到试卷',
            ], 404);
        }

        if (!$studentId) {
            $studentId = $paper->student_id;
        }

        if (!$studentId) {
            return response()->json([
                'success' => false,
                'message' => '缺少 student_id',
            ], 422);
        }

        $pdfUrl = $pdfExportService->generateAnalysisReportPdf($paperId, $studentId);
        if (!$pdfUrl) {
            return response()->json([
                'success' => false,
                'message' => '生成学情报告失败',
            ], 500);
        }

        $viewUrl = URL::to("/admin/exam-analysis?paperId={$paperId}&studentId={$studentId}");

        return response()->json([
            'success' => true,
            'message' => '学情报告生成成功',
            'data' => [
                'paper_id' => $paperId,
                'student_id' => $studentId,
                'pdf_url' => $pdfUrl,
                'analysis_url' => $viewUrl,
            ],
        ], 200, [], JSON_UNESCAPED_SLASHES);
    }
}
