<?php

namespace App\Http\Controllers\Api\Documentation;

use App\Http\Controllers\Controller;
use App\Services\Docs\DocsCatalogService;
use App\Services\Docs\OpenApiRouteExporter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

/**
 * Docs hub + multi-spec Swagger catalog (JSON for SPA).
 */
class DocsCatalogController extends Controller
{
    public function __construct(
        private DocsCatalogService $catalog,
    ) {}

    public function index(Request $request)
    {
        if (! $request->expectsJson()) {
            return redirect()->to((string) config('docs.client_url', url('/docs')));
        }

        return response()->json([
            'status' => true,
            'data' => $this->catalog->indexPayload(),
        ]);
    }

    public function ui(): View
    {
        return view('docs.swagger');
    }

    public function swagger(): JsonResponse
    {
        return response()->json([
            'status' => true,
            'data' => $this->catalog->swaggerSpecsPayload(),
        ]);
    }

    /**
     * Merged OpenAPI spec (static openapi.json + live route merge).
     */
    public function swaggerMergedJson(): JsonResponse
    {
        $path = resource_path('docs/openapi.json');
        abort_unless(is_file($path), 404);

        $spec = app(OpenApiRouteExporter::class)->exportFromFile($path);

        return response()->json($spec, 200, [
            'Content-Type' => 'application/json',
            'Cache-Control' => 'no-store, max-age=0',
        ]);
    }
}
