const schema = require('./data/eds-c-data-attributes.schema.json');
const exampleJson = require('./data/eds-c-data-attributes.example.json');
const fs = require('node:fs');
const path = require('node:path');
const componentTemplate = '<div {{> eds-c-data-attributes }}> </div>';
const Ajv = require('ajv');
const ajv = new Ajv();
const handlebars = require('handlebars');

const {findTemplates} = require('../../development/tests/templateLoader.js');
findTemplates(['eds-c-data-attributes']).load(handlebars);

const componentHbs = handlebars.compile(componentTemplate);
const renderedComponent = componentHbs({dataAttributes: exampleJson});

describe('EDS Component Data attributes', () => {
    test('docs file exists', () => {
        const exists = fs.existsSync(path.resolve(__dirname, 'docs.md'));
        expect(exists).toBe(true);
    });
});

describe('Data attributes Schema Validation and Accessibility Test', () => {
    
    const { configureAxe, toHaveNoViolations } = require('jest-axe');
    expect.extend(toHaveNoViolations);
    
    const axe = configureAxe({
        rules: {
            region: { enabled: false }
        }
    });

    test('Example data matches schema', () => {
        const validate = ajv.compile(schema);
        const valid = validate(exampleJson);

        if (!valid) {
            // Extract and format the Ajv validation errors
            const errors = validate.errors.map((error) => ajv.errorsText([error])).join('\n');
            throw new Error(errors);
        }

        expect(valid).toBeTruthy();
    });

    test('Data attributes are correct', () => {
        document.body.innerHTML = renderedComponent;
        const container = document.querySelector('div');
        const dataAttributes = Object.keys(container.dataset);
        expect(dataAttributes.length).toBe(4);
        expect(container.getAttribute('data-test')).toEqual('yes-test');
        expect(container.getAttribute('data-track-context')).toEqual('springer-link');
        expect(container.getAttribute('data-track-content-type')).toEqual('collection');
        expect(container.getAttribute('data-track-label')).toEqual('collection');
    });
});