import { isToken, tokens } from '@preply/ds-core';
import {
    TOKEN_COLOR_SCHEME_AWARE_FIELD,
    TOKEN_ID_FIELD,
    TOKEN_TYPE_FIELD,
    Token,
} from '@preply/ds-core-types';

import { ExtendedToken, TokenTree, TokenTreeNode } from '../types';

const extendedToken = (name: string, token: Token): Omit<ExtendedToken, 'value'> => {
    return {
        token,
        name,
        id: token[TOKEN_ID_FIELD],
        type: token[TOKEN_TYPE_FIELD],
        colorSchemeAware: !!token[TOKEN_COLOR_SCHEME_AWARE_FIELD],
    };
};

const flat = (namespace: string, node: TokenTreeNode): Omit<ExtendedToken, 'value'>[] => {
    return Object.entries(node).flatMap(([key, child]) => {
        const chidKey = `${namespace}.${key}`;
        if (isToken(child)) {
            return [extendedToken(chidKey, child)];
        }
        return flat(chidKey, child);
    });
};

const flatten = (node: TokenTree): Omit<ExtendedToken, 'value'>[] => {
    return Object.entries(node).flatMap(([namespace, child]) => flat(namespace, child));
};

export const FLAT_TOKENS = flatten(tokens);
