<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Paper;
use App\Services\PaperPayloadService;
use Illuminate\Http\Request;

class PaperJsonController extends Controller
{
    public function show(Request $request, string $paperId)
    {
        $paper = Paper::with('questions')->find($paperId);
        if (!$paper) {
            return response()->json([
                'success' => false,
                'message' => 'Paper not found',
            ], 404);
        }

        $payload = app(PaperPayloadService::class)->buildPaperApiPayload($paper);

        if ($request->boolean('download')) {
            $filename = sprintf('paper_%s.json', $paperId);
            return response(
                json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
                200,
                [
                    'Content-Type' => 'application/json; charset=utf-8',
                    'Content-Disposition' => 'attachment; filename="' . $filename . '"',
                ]
            );
        }

        return response()->json($payload);
    }

}
