import { parseResolveInfo } from 'graphql-parse-resolve-info';

import { getIdsBySlug } from '../cache.js';

import {
	fetchEntities,
	fetchEntitiesById,
} from '../entities.js';

export async function fetchEntitiesApi(req, res) {
	const entities = await fetchEntities(req.query);

	res.send(entities);
}

export const entitiesSchema = `
	extend type Query {
		entities(
			query: String
			type: String
			order: [String]
			limit: Int! = 30
			page: Int! = 1
		): EntitiesResult

		entity(
			slug: String!
		): Entity

		entitiesBySlug(
			slugs: [String]!
		): [Entity]

		entitiesById(
			ids: [Int]!
		): [Entity]
	}

	type EntitiesResult {
		nodes: [Entity!]!
	}

	type Entity {
		id: Int!
		name: String
		slug: String
		url: String
		type: String
		parent: Entity
		children: [Entity!]!
	}
`;

export async function fetchEntitiesGraphql(query, _req) {
	const entities = await fetchEntities(query);

	return {
		nodes: entities,
	};
}

export async function fetchEntitiesByIdGraphql(query, req, info) {
	const entityIds = query.ids || await getIdsBySlug([].concat(query.slug, query.slugs).filter(Boolean), 'entities');
	const parsedContext = parseResolveInfo(info);

	const entities = await fetchEntitiesById(entityIds, {
		includeChildren: Object.hasOwn(parsedContext.fieldsByTypeName.Entity, 'children'),
	});

	if (query.slugs || query.ids) {
		return entities;
	}

	return entities[0];
}
