import Ajv, { type JSONSchemaType } from "ajv";
import addFormats from "ajv-formats";
import { type Config } from "./types/config";
import { prettify } from "awesome-ajv-errors";

export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    const fs = await import("fs");

    const phoneRegex = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/;

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

    ajv.addFormat("phone", {
      validate: (data: string) => phoneRegex.test(data),
    });

    const configSchema: JSONSchemaType<Config> = {
      type: "object",
      additionalProperties: false,
      required: ["name"],
      properties: {
        socials: {
          type: "object",
          additionalProperties: false,
          nullable: true,
          properties: {
            matrix: { type: "string", nullable: true },
            linkedin: { type: "string", nullable: true },
            gitea: { type: "string", format: "uri", nullable: true },
            github: { type: "string", nullable: true },
            instagram: { type: "string", nullable: true },
            custom: { type: "string", format: "uri", nullable: true },
          },
        },
        projects: {
          type: "array",
          items: {
            type: "object",
            additionalProperties: false,
            properties: {
              name: { type: "string" },
              description: { type: "string" },
              date: { type: "string", format: "date" },
              links: {
                type: "array",
                items: { type: "string", format: "uri" },
                nullable: true,
              },
              images: {
                type: "array",
                items: { type: "string" },
                nullable: true,
              },
              tags: {
                type: "array",
                items: { type: "string" },
                nullable: true,
              },
            },
            required: ["name", "description", "date"],
          },
          nullable: true,
        },
        phoneNumber: {
          type: "string",
          format: "phone",
          nullable: true,
        },
        fallbackUrl: {
          type: "string",
          format: "uri",
          nullable: true,
        },
        name: {
          type: "array",
          items: [{ type: "string" }, { type: "string" }],
          minItems: 2,
          maxItems: 2,
        },
        status: { type: "string", nullable: true },
        location: { type: "string", nullable: true },
      },
    };

    const config = JSON.parse(
      fs.readFileSync("public/config/config.json", "utf-8")
    );

    const validateConfig = ajv.compile(configSchema);

    if (!validateConfig(config)) {
      console.error(prettify(validateConfig, { data: config }));
      process.exit(1);
    }
  }
}
