import fs from "fs-extra";
import path from "path";

// Create the schema validator generator
import Ajv from "ajv";
import addFormats from "ajv-formats";

const ajv = new Ajv({
  allErrors: true,
  strict: false,
});
addFormats(ajv);

const schemasDir = path.resolve(__dirname, "schemas");
// The schema files
const schemaFilePaths = fs.readdirSync(schemasDir);

// Dictionary to keep the connection between a schema file and the loaded schema object
const schemas: Record<string, object> = {};

// Load all the schema files and populate the dictionary and the validator
schemaFilePaths
  .filter((schemaFilePath) => schemaFilePath.endsWith(".json")) // Try to read only json files
  .forEach((schemaFilePath) => {
    const s = fs.readFileSync(path.resolve(schemasDir, schemaFilePath), "utf-8");
    const schema = JSON.parse(s);
    ajv.addSchema(schema);
    schemas[schemaFilePath] = schema;
  });

// Create the validators
const moduleValidator = ajv.compile(schemas["Module.json"]);

// Load the file names
const samplesDir = path.join(__dirname, "samples");
const sampleFilenames = fs.readdirSync(samplesDir).map((f) => path.join(samplesDir, f));

test.each(sampleFilenames)("%s should be valid", async (sampleFilename) => {
  const sample = JSON.parse(await fs.readFile(sampleFilename, "utf8"));

  const validationResult = moduleValidator(sample);
  if (moduleValidator.errors) {
    throw moduleValidator.errors;
  }

  expect(validationResult).toBe(true);
});
