import { colorSchemes } from '@preply/ds-web-core';
import { themes } from '@preply/ds-web-root';

import { flattenTokens } from '../providers/TokenSearchProvider';

import { tokenRenderer } from './token-type.renderer';
import { filterTokens } from './token.filter';

describe('token-type.renderer.test', () => {
    // If this test fails, chances are you added a new token without adding it to `typeFromPrefix`.
    // As a result, the Token Explorer page is broken.
    it('should return a token renderer for all the available tokens', () => {
        const theme = themes.find(t => t.name === 'tokyo-ui');
        // There is nod need to test all the color schemes since the internal DS validations already
        // check that the color-scheme-aware tokens provide a value for every single color scheme
        const colorScheme = colorSchemes[0];

        // Avoids false positive
        expect(theme).toBeDefined();

        // This is a TS-only related check since theme could be undefined from a TS perspective
        if (!theme) throw new Error('theme is undefined');

        // Check that the renderer throws an error when a color-scheme-unaware token is not found
        // This is useful to avoid false positives later in the test
        expect(() =>
            tokenRenderer({
                token: ['base', 'b357d0', true],
                name: 'unexisting.token',
                id: '',
                type: 'base',
                colorSchemeAware: false,
                value: '#6A100C',
            }),
        ).toThrowError(new Error('No renderer for token "unexisting.token".'));

        // Check that the renderer throws an error when a color-scheme-aware token is not found
        // This is useful to avoid false positives later in the test
        expect(() =>
            tokenRenderer({
                token: ['base', 'b357d0', true],
                name: 'unexisting.token',
                id: '',
                type: 'base',
                colorSchemeAware: true,
                value: '#6A100C',
            }),
        ).toThrowError(new Error('No renderer for token "unexisting.token".'));

        const tokens = flattenTokens(theme, colorScheme);

        // COLOR SCHEME AWARE TOKENS
        const colorSchemeAwareTokens = filterTokens(tokens, '', true);

        // To avoid false positives because the filter returns nothing...
        expect(colorSchemeAwareTokens.length).toBeGreaterThan(0);

        colorSchemeAwareTokens.forEach(token => {
            expect(() => tokenRenderer(token)).not.toThrow();
        });

        // COLOR SCHEME UNAWARE TOKENS
        const colorSchemeUnawareTokens = filterTokens(tokens, '', false);

        // To avoid false positives because the filter returns nothing...
        expect(colorSchemeUnawareTokens.length).toBeGreaterThan(0);

        colorSchemeUnawareTokens.forEach(token => {
            expect(() => tokenRenderer(token)).not.toThrow();
        });
    });
});
