const schema = require('./data/eds-c-textarea.schema.json');
const exampleJson = require('./data/eds-c-textarea.example.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 {findTemplates} = require('../../development/tests/templateLoader.js');
findTemplates(['eds-c-textarea', 'eds-c-label', 'eds-c-hint', 'eds-c-error-message']).load(handlebars);

const componentTemplate = '{{> eds-c-textarea}}';
const componentHbs = handlebars.compile(componentTemplate);
const renderedComponent = componentHbs(exampleJson);

describe('Label 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', () => {
        // Add other schema to Ajv instance
        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();
    });
});