import type { Cloudly } from '../classes.cloudly.js';

export const installDemoData = async (cloudlyRef: Cloudly) => {
  
  // ================================================================================
  // SECRETS

  const demoDataSecrets = await import('./demo.data.secrets.js');

  const secretGroups = await cloudlyRef.secretManager.CSecretGroup.getInstances({});
  for (const secretGroup of secretGroups) {
    await secretGroup.delete();
  }

  const secretBundles = await cloudlyRef.secretManager.CSecretBundle.getInstances({});
  for (const secretBundle of secretBundles) {
    await secretBundle.delete();
  }

  for (const secretData of demoDataSecrets.demoSecretGroups) {
    const secretGroup = new cloudlyRef.secretManager.CSecretGroup();
    Object.assign(secretGroup, secretData);
    await secretGroup.save();
  }
  for (const secretBundleData of demoDataSecrets.demoConfigBundles) {
    const secretBundle = new cloudlyRef.secretManager.CSecretBundle();
    Object.assign(secretBundle, secretBundleData);
    await secretBundle.save();
  }

  // ================================================================================
  // CLUSTERS
  const clusters = await cloudlyRef.clusterManager.CCluster.getInstances({});
  for (const cluster of clusters) {
    await cluster.delete();
  }

  // ================================================================================
  // USERS
  const users = await cloudlyRef.authManager.CUser.getInstances({});
  for (const user of users) {
    await user.delete();
  }

  const demoDataUsers = await import('./demo.data.users.js');
  for (const user of await demoDataUsers.getUsers(cloudlyRef)) {
    const userInstance = new cloudlyRef.authManager.CUser();
    Object.assign(userInstance, user);
    await userInstance.save();
  }

  // ================================================================================
  // IMAGES
  const images = await cloudlyRef.imageManager.CImage.getInstances({});
  for (const image of images) {
    await image.delete();
  }

  const demoDataImages = await import('./demo.data.images.js');
  for (const image of demoDataImages.demoImages) {
    const imageInstance = new cloudlyRef.imageManager.CImage();
    Object.assign(imageInstance, image);
    await imageInstance.save();
  }
}