<?php

namespace App\Http\Controllers;

use App\Support\GraphqlReadOnlySchema;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GraphqlReadOnlyController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $payload = $request->validate([
            'query' => ['required', 'string', 'max:30000'],
            'variables' => ['nullable', 'array'],
        ]);

        try {
            return response()->json(GraphqlReadOnlySchema::execute(
                (string) $payload['query'],
                (array) ($payload['variables'] ?? [])
            ));
        } catch (\InvalidArgumentException $e) {
            return response()->json([
                'errors' => [
                    ['message' => $e->getMessage()],
                ],
            ], 422);
        } catch (\Throwable $e) {
            report($e);

            return response()->json([
                'errors' => [
                    ['message' => 'Read-only GraphQL request failed.'],
                ],
            ], 500);
        }
    }
}
