<?php

declare(strict_types=1);

namespace App\Framework\GraphQL\Execution;

use App\Framework\GraphQL\DataLoader\DataLoaderRegistry;
use App\Framework\Http\Request\HttpRequest;

/**
 * Execution context for GraphQL query
 *
 * Contains request-scoped data and DataLoader registry
 */
final readonly class ExecutionContext
{
    public function __construct(
        public DataLoaderRegistry $dataLoaderRegistry,
        public ?HttpRequest $request = null,
        public mixed $user = null
    ) {
    }

    public static function create(?HttpRequest $request = null): self
    {
        return new self(
            dataLoaderRegistry: new DataLoaderRegistry(),
            request: $request
        );
    }

    /**
     * Get DataLoader by key
     */
    public function getLoader(string $key): ?\App\Framework\GraphQL\DataLoader\DataLoader
    {
        return $this->dataLoaderRegistry->get($key);
    }

    /**
     * Create or get DataLoader
     *
     * @param \Closure(array): array $batchLoadFn
     */
    public function loader(string $key, \Closure $batchLoadFn): \App\Framework\GraphQL\DataLoader\DataLoader
    {
        return $this->dataLoaderRegistry->getOrCreate($key, $batchLoadFn);
    }
}
