/**
 * GraphQL Transformer
 * 
 * Converts parsed GraphQL schema to BrainfishCollection format
 * for integration with the existing documentation system.
 */ import { makeBrainfishCollection } from '../../factories';
import { formatTypeRef } from './types';
import { generateExampleVariables, generateOperationQuery } from './parser';
// ============================================================================
// GraphQL to REST-like Request Conversion
// ============================================================================
/**
 * Convert a GraphQL operation to a REST-like request for the playground
 * This allows us to reuse the existing API client UI
 */ function convertOperationToRESTRequest(operation, endpoint) {
    // Generate the query string
    const query = generateOperationQuery(operation);
    // Generate example variables
    const variables = generateExampleVariables(operation);
    // GraphQL always uses POST with JSON body
    const body = JSON.stringify({
        query,
        variables,
        operationName: operation.name
    }, null, 2);
    return {
        id: operation.id,
        name: operation.name,
        description: operation.description || formatOperationDescription(operation),
        method: 'POST',
        endpoint,
        params: [],
        headers: [
            {
                key: 'Content-Type',
                value: 'application/json',
                active: true,
                description: 'GraphQL requests use JSON'
            }
        ],
        auth: {
            authType: 'inherit',
            authActive: true
        },
        body: {
            contentType: 'application/json',
            body
        },
        requestVariables: operation.args.map((arg)=>({
                key: arg.name,
                value: JSON.stringify(generateExampleVariables({
                    ...operation,
                    args: [
                        arg
                    ]
                })[arg.name]),
                active: true
            })),
        responses: {},
        tags: [
            operation.operationType
        ]
    };
}
/**
 * Format a description for an operation based on its signature
 */ function formatOperationDescription(operation) {
    const args = operation.args.map((arg)=>`${arg.name}: ${formatTypeRef(arg.type)}`).join(', ');
    const returnType = formatTypeRef(operation.returnType);
    return `${operation.operationType} ${operation.name}(${args}): ${returnType}`;
}
// ============================================================================
// Main Transformer Functions
// ============================================================================
/**
 * Convert GraphQL schema to a BrainfishGraphQLCollection
 */ export function convertGraphQLToCollection(schema, name, endpoint, description) {
    // Convert operations to our request format
    const queries = schema.queries.map((op)=>({
            id: op.id,
            name: op.name,
            description: op.description,
            operationType: 'query',
            query: generateOperationQuery(op),
            variables: op.args,
            returnType: op.returnType,
            tags: [
                'Query'
            ],
            exampleVariables: generateExampleVariables(op)
        }));
    const mutations = schema.mutations.map((op)=>({
            id: op.id,
            name: op.name,
            description: op.description,
            operationType: 'mutation',
            query: generateOperationQuery(op),
            variables: op.args,
            returnType: op.returnType,
            tags: [
                'Mutation'
            ],
            exampleVariables: generateExampleVariables(op)
        }));
    const subscriptions = schema.subscriptions.map((op)=>({
            id: op.id,
            name: op.name,
            description: op.description,
            operationType: 'subscription',
            query: generateOperationQuery(op),
            variables: op.args,
            returnType: op.returnType,
            tags: [
                'Subscription'
            ],
            exampleVariables: generateExampleVariables(op)
        }));
    // Extract custom types (exclude built-in scalars)
    const customTypes = Object.values(schema.types).filter((type)=>![
            'String',
            'Int',
            'Float',
            'Boolean',
            'ID'
        ].includes(type.name));
    return {
        id: `graphql-${name.toLowerCase().replace(/\s+/g, '-')}`,
        name,
        description: description || schema.info.description,
        endpoint,
        schema,
        queries,
        mutations,
        subscriptions,
        types: customTypes
    };
}
/**
 * Convert GraphQL schema to BrainfishCollection format
 * This allows integration with the existing REST-based UI
 */ export function convertGraphQLToBrainfishCollection(schema, name, endpoint, description) {
    // Create folders for each operation type
    const queryFolder = makeBrainfishCollection({
        name: 'Queries',
        description: 'GraphQL Query operations',
        requests: schema.queries.map((op)=>convertOperationToRESTRequest(op, endpoint)),
        folders: [],
        variables: [],
        auth: {
            authType: 'none',
            authActive: false
        },
        headers: []
    });
    const mutationFolder = makeBrainfishCollection({
        name: 'Mutations',
        description: 'GraphQL Mutation operations',
        requests: schema.mutations.map((op)=>convertOperationToRESTRequest(op, endpoint)),
        folders: [],
        variables: [],
        auth: {
            authType: 'none',
            authActive: false
        },
        headers: []
    });
    const subscriptionFolder = makeBrainfishCollection({
        name: 'Subscriptions',
        description: 'GraphQL Subscription operations',
        requests: schema.subscriptions.map((op)=>convertOperationToRESTRequest(op, endpoint)),
        folders: [],
        variables: [],
        auth: {
            authType: 'none',
            authActive: false
        },
        headers: []
    });
    // Only include folders that have operations
    const folders = [];
    if (schema.queries.length > 0) folders.push(queryFolder);
    if (schema.mutations.length > 0) folders.push(mutationFolder);
    if (schema.subscriptions.length > 0) folders.push(subscriptionFolder);
    return makeBrainfishCollection({
        name,
        description: description || schema.info.description || 'GraphQL API',
        folders,
        requests: [],
        variables: [],
        auth: {
            authType: 'none',
            authActive: false
        },
        headers: [
            {
                key: 'Content-Type',
                value: 'application/json',
                active: true,
                description: 'GraphQL requests use JSON'
            }
        ]
    });
}
/**
 * Merge GraphQL collection with existing REST collection
 */ export function mergeWithRESTCollection(restCollection, graphqlSchema, graphqlEndpoint) {
    const graphqlCollection = convertGraphQLToBrainfishCollection(graphqlSchema, 'GraphQL', graphqlEndpoint);
    return {
        ...restCollection,
        folders: [
            ...restCollection.folders,
            graphqlCollection
        ]
    };
}
