const require_rolldown_runtime = require('../../../_virtual/rolldown_runtime.js');
const require_runtime_manifest = require('../../../runtime/manifest.js');
const require_common_encoding = require('../../../common/encoding.js');
const require_common_onInit = require('../../../common/onInit.js');
const require_common_providers_https = require('../../../common/providers/https.js');
const require_v2_trace = require('../../trace.js');
const require_v2_options = require('../../options.js');
let express = require("express");
express = require_rolldown_runtime.__toESM(express);
let fs = require("fs");
fs = require_rolldown_runtime.__toESM(fs);
let __apollo_server = require("@apollo/server");
__apollo_server = require_rolldown_runtime.__toESM(__apollo_server);
let __as_integrations_express4 = require("@as-integrations/express4");
__as_integrations_express4 = require_rolldown_runtime.__toESM(__as_integrations_express4);

//#region src/v2/providers/dataconnect/graphql.ts
var graphql_exports = /* @__PURE__ */ require_rolldown_runtime.__export({
	initGraphqlServer: () => initGraphqlServer,
	onGraphRequest: () => onGraphRequest
});
const FIREBASE_AUTH_HEADER = "X-Firebase-Auth-Token";
const PRELUDE_GQL = [
	"scalar UUID",
	"scalar Int64",
	"scalar Any",
	"scalar Void",
	"scalar True",
	"scalar Date",
	"scalar Timestamp"
].join("\n");
/** @hidden */
async function initGraphqlServer(opts) {
	if (!opts.schema && !opts.schemaFilePath || opts.schema && opts.schemaFilePath) {
		throw new Error("Exactly one of 'schema' or 'schemaFilePath' must be provided.");
	}
	if (opts.schemaFilePath) {
		opts.schema = fs.default.readFileSync(opts.schemaFilePath, "utf-8");
	}
	const schemaWithPrelude = PRELUDE_GQL + "\n" + opts.schema;
	if (!opts.resolvers.query && !opts.resolvers.mutation) {
		throw new Error("At least one query or mutation resolver must be provided.");
	}
	const apolloResolvers = {};
	if (opts.resolvers.query) {
		apolloResolvers.Query = opts.resolvers.query;
	}
	if (opts.resolvers.mutation) {
		apolloResolvers.Mutation = opts.resolvers.mutation;
	}
	try {
		const serverPromise = (async () => {
			const app = (0, express.default)();
			const server = new __apollo_server.ApolloServer({
				typeDefs: schemaWithPrelude,
				resolvers: apolloResolvers
			});
			await server.start();
			app.use(`/${opts.path ?? "graphql"}`, express.default.json(), (0, __as_integrations_express4.expressMiddleware)(server, { context: ({ req }) => Promise.resolve({ auth: { token: req.header(FIREBASE_AUTH_HEADER) } }) }));
			return app;
		})();
		return serverPromise;
	} catch (e) {
		if (e instanceof Error) {
			throw new Error("Error initializing GraphQL server: " + e.message);
		} else {
			throw e;
		}
	}
}
/**
* Handles HTTPS GraphQL requests.
* @param {GraphqlServerOptions} opts - Options for configuring the GraphQL server.
* @returns {HttpsFunction} A function you can export and deploy.
*/
function onGraphRequest(opts) {
	let serverPromise = null;
	const handler = require_v2_trace.wrapTraceContext(require_common_onInit.withInit(require_common_providers_https.withErrorHandler(async (req, res) => {
		serverPromise = serverPromise ?? initGraphqlServer(opts);
		const app = await serverPromise;
		app(req, res);
	})));
	const globalOpts = require_v2_options.getGlobalOptions();
	const baseOpts = require_v2_options.optionsToEndpoint(globalOpts);
	const specificOpts = require_v2_options.optionsToEndpoint(opts);
	const endpoint = {
		...require_runtime_manifest.initV2Endpoint(globalOpts, opts),
		platform: "gcfv2",
		...baseOpts,
		...specificOpts,
		labels: {
			...baseOpts?.labels,
			...specificOpts?.labels
		},
		dataConnectGraphqlTrigger: {}
	};
	require_common_encoding.convertIfPresent(endpoint.dataConnectGraphqlTrigger, globalOpts, "invoker", "invoker", require_common_encoding.convertInvoker);
	require_common_encoding.convertIfPresent(endpoint.dataConnectGraphqlTrigger, opts, "invoker", "invoker", require_common_encoding.convertInvoker);
	if (opts.schemaFilePath) {
		endpoint.dataConnectGraphqlTrigger.schemaFilePath = opts.schemaFilePath;
	}
	handler.__endpoint = endpoint;
	return handler;
}

//#endregion
Object.defineProperty(exports, 'graphql_exports', {
  enumerable: true,
  get: function () {
    return graphql_exports;
  }
});
exports.initGraphqlServer = initGraphqlServer;
exports.onGraphRequest = onGraphRequest;