const schema = require('./data/eds-c-checkbox.schema.json');
const exampleJson = require('./data/eds-c-checkbox.example.json');
const fs = require('fs');
const path = require('path');
const filenames = fs.readdirSync(__dirname);
const componentTemplate = fs.readFileSync(path.resolve(__dirname, 'eds-c-checkbox.hbs'), 'utf8');
const componentsDir = path.join(__dirname, '..');
const hintTemplatePath = path.resolve(componentsDir, 'eds-c-hint', 'eds-c-hint.hbs');
const hintTemplate = fs.readFileSync(hintTemplatePath, 'utf8');
const inputSchema = require('../eds-c-input/data/eds-c-input.schema.json');
const hintSchema = require('../eds-c-hint/data/eds-c-hint.schema.json');
const labelSchema = require('../eds-c-label/data/eds-c-label.schema.json');
const errorMessageSchema = require('../eds-c-error-message/data/eds-c-error-message.schema.json');
const Ajv = require("ajv");
const ajv = new Ajv();
const handlebars = require('handlebars');

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

describe('Label 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', () => {
        // Add other schema to Ajv instance
        ajv.addSchema(inputSchema, 'inputSchema');
        ajv.addSchema(labelSchema, 'labelSchema');
        ajv.addSchema(hintSchema, 'hintSchema');
        ajv.addSchema(errorMessageSchema, 'errorMessageSchema');
        
        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('Template can be compiled and rendered', () => {
        document.body.innerHTML = renderedComponent;
        const container = document.querySelector('*');
        expect(container).toBeDefined();
    });
    
    test('Template passes basic HTML accessibility', async () => {
        expect(await axe(renderedComponent)).toHaveNoViolations();
    });
});