import ApolloClient from 'apollo-client';
import gql from 'graphql-tag';

import { NOT_FOUND_NAME } from './vars';
import { ResolvedPath } from './PageRouter';

const QUERY = gql`
    query urlResolver($pathname: String = "/baby") {
        urlResolver(url: $pathname) {
            redirectCode
            id
            type
            relative_url
        }
    }
`;

export async function magentoPageResolver(
    pathname: string,
    pages: string[],
    client: ApolloClient<any>,
): Promise<ResolvedPath> {
    return client
        .query({ query: QUERY, variables: { pathname } })
        .then((res) => {
            if (res?.data?.urlResolver) {
                const { id, type, redirectCode } = res.data.urlResolver;
                if (type) {
                    const pageName = urlEntityToComponentName(type);
                    const chunkName = `${pageName}_Page`;
                    return {
                        pageName,
                        id,
                        redirectCode,
                        pathname,
                        chunkName,
                    };
                }
            }
            return { pageName: NOT_FOUND_NAME, pathname, chunkName: `${NOT_FOUND_NAME}_Page` };
        })
        .catch((e) => {
            console.error(e);
            return { pageName: NOT_FOUND_NAME, pathname, chunkName: `${NOT_FOUND_NAME}_Page` };
        });
}

export function urlEntityToComponentName(urlEntity: string): string {
    return urlEntity
        .toLowerCase()
        .split('_')
        .map((name) => name[0].toUpperCase() + name.slice(1))
        .join('');
}

export function pathSegmentToComponentName(path: string): string {
    return path
        .toLowerCase()
        .split('-')
        .map((name) => name[0].toUpperCase() + name.slice(1))
        .join('');
}
