const schema = require('./data/eds-c-error-summary.schema.json');
const exampleJson = require('./data/eds-c-error-summary.example.json');
const fs = require('node:fs');
const path = require('node:path');
const filenames = fs.readdirSync(__dirname);
const componentTemplate = fs.readFileSync(path.resolve(__dirname, 'eds-c-error-summary.hbs'), 'utf8');
const Ajv = require('ajv');
const ajv = new Ajv();
const handlebars = require('handlebars');

const componentHbs = handlebars.compile(componentTemplate);
const renderedComponent = componentHbs(exampleJson);

describe('Error Summary Schema Validation and Accessibility Test', () => {
    filenames.forEach(function (filename) {
        var matches = /^([^.]+).hbs$/.exec(filename);
        if (!matches) {
            return;
        }
        var name = matches[1];
        var template = fs.readFileSync(__dirname + '/' + filename, 'utf8');
        handlebars.registerPartial(name, template);
    });
    
    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('Title should be rendered correctly', () => {
        document.body.innerHTML = renderedComponent;
        const container = document.querySelector('.eds-c-error-summary__title');
        expect(container.getAttribute('id')).toBe('summary');
        expect(container.textContent.replace(/\s+/g, ' ').trim()).toBe('There is a problem');
    });

    test('Summary aria-labelledby should be set correctly', () => {
        document.body.innerHTML = renderedComponent;
        const titleElement = document.querySelector('.eds-c-error-summary');
        expect(titleElement.getAttribute('aria-labelledby')).toBe('summary');
    });

    test('Error should be rendered correctly', () => {
        document.body.innerHTML = renderedComponent;
        const errorElement = document.querySelector('.eds-c-error-summary__errors li a');
        const errorElements = document.querySelectorAll('.eds-c-error-summary__errors li a');
        expect(errorElement.getAttribute('href')).toBe('#your-name');
        expect(errorElement.textContent.replace(/\s+/g, ' ').trim()).toBe('Enter your full name');
        expect([...errorElements].length).toBe(2);
    });
    
    test('Template passes basic HTML accessibility', async () => {
        expect(await axe(renderedComponent)).toHaveNoViolations();
    });
});