export const validateManifest = (data, accessToken) => {
  const errors = [];

  if (!accessToken || accessToken.length === 0) {
    throw new Error("Access token required");
  }

  if (!data) {
    throw new Error("Missing manifest data");
  }

  if (!data.name || data.name.length === 0) {
    errors.push("name");
  }

  if (!data.version || data.version.length === 0) {
    errors.push("version");
  }

  if (!data.description || data.description.length === 0) {
    errors.push("description");
  }

  if (!data.release_notes || data.release_notes.length === 0) {
    errors.push("release notes");
  }

  if (errors.length > 0)
    throw new Error(`package ${errors.join(", ")} required`);
};

export const validateManifestECUs = (ecus) => {
  const ecuKeys = {};

  if (!ecus || ecus.length === 0) throw new Error("ECUs required");

  ecus.forEach((ecu) => validateManifestECU(ecu, ecuKeys));
};

const validateManifestECU = (data, keys) => {
  const errors = [];
  const fileKeys = {};

  if (!data) {
    throw new Error("manifest ECU data required");
  }

  if (!data.name || data.name.length === 0) {
    errors.push("name");
  }

  if (!data.version || data.version.length === 0) {
    errors.push("version");
  }

  if (!data.part_number || data.part_number.length === 0) {
    errors.push("part number");
  }

  if (!data.files || data.files.length === 0) {
    errors.push("files");
  }

  const key = `${data.name} ${data.version} ${data.part_number}`;
  if (!keys[key]) {
    keys[key] = true;
  } else {
    throw new Error(`ECU ${key} already exists`);
  }

  if (errors.length > 0)
    throw new Error(`ECU ${data.name} ${errors.join(", ")} required`);

  data.files.forEach((file) => validateFile(data.name, file, fileKeys));
};

const validateFile = (ecu, file, keys) => {
  const errors = [];

  if (!file) {
    throw new Error("File data required");
  }

  if (!file.filename || file.filename.length === 0) {
    errors.push("filename");
  }

  if (!file.offset || file.offset.length === 0) {
    errors.push("offset");
  }

  const key = `${file.filename} ${file.version}`;
  if (!keys[key]) {
    keys[key] = true;
  } else {
    throw new Error(`${ecu} ${key} already exists`);
  }

  if (errors.length > 0)
    throw new Error(`${ecu} ${file.filename} ${errors.join(", ")} required`);
};
