import { MetaService } from "../services/meta.service.js";
async function withMeta(entities, entityType, userId, includePrivate = false) {
  const isArray = Array.isArray(entities);
  const entityList = isArray ? entities : [entities];
  const entitiesWithMeta = await Promise.all(
    entityList.map(async (entity) => {
      const meta = await MetaService.getEntityMetas(
        entityType,
        entity.id,
        userId,
        includePrivate
      );
      return {
        ...entity,
        meta
      };
    })
  );
  return isArray ? entitiesWithMeta : entitiesWithMeta[0];
}
async function copyEntityMetas(entityType, sourceEntityId, targetEntityId, userId, metaKeys) {
  const sourceMetas = await MetaService.getEntityMetas(entityType, sourceEntityId, userId, true);
  const metasToCopy = metaKeys ? Object.fromEntries(Object.entries(sourceMetas).filter(([key]) => metaKeys.includes(key))) : sourceMetas;
  if (Object.keys(metasToCopy).length > 0) {
    await MetaService.setBulkEntityMetas(entityType, targetEntityId, metasToCopy, userId);
  }
}
function validateBasicMetas(metas) {
  const errors = [];
  for (const [key, value] of Object.entries(metas)) {
    if (!key || key.trim() === "") {
      errors.push("Meta key cannot be empty");
    }
    if (key.length > 100) {
      errors.push(`Meta key '${key}' is too long (max 100 characters)`);
    }
    try {
      const valueSize = JSON.stringify(value).length;
      if (valueSize > 1048576) {
        errors.push(`Meta value for '${key}' is too large (max 1MB)`);
      }
    } catch {
      errors.push(`Meta value for '${key}' is not serializable`);
    }
  }
  return {
    isValid: errors.length === 0,
    errors
  };
}
export {
  copyEntityMetas,
  validateBasicMetas,
  withMeta
};
