import { tap, expect } from '@push.rocks/tapbundle';
import * as helpers from './helpers/index.js';

import * as cloudly from '../ts/index.js';
import * as cloudlyApiClient from '../ts_apiclient/index.js';
import { Image } from '../ts_apiclient/classes.image.js';

let testCloudly: cloudly.Cloudly;
let testClient: cloudlyApiClient.CloudlyApiClient;

tap.preTask('should start cloudly', async () => {
  testCloudly = await helpers.createCloudly();
  await testCloudly.start();
});

tap.preTask('should create a new machine user for testing', async () => {
  const machineUser = new testCloudly.authManager.CUser();
  machineUser.id = await testCloudly.authManager.CUser.getNewId();
  machineUser.data = {
    type: 'machine',
    username: 'test',
    password: 'test',
    tokens: [{
      token: 'test',
      expiresAt: Date.now() + 3600 * 1000 * 24 * 365,
      assignedRoles: ['admin'],
    }],
    role: 'admin',
  };
  await machineUser.save();
});

tap.test('should create a new cloudlyApiClient', async () => {
  testClient = new cloudlyApiClient.CloudlyApiClient({
    registerAs: 'api',
    cloudlyUrl: `http://${helpers.testCloudlyConfig.publicUrl}:${helpers.testCloudlyConfig.publicPort}`,
  });
  await testClient.start();
  expect(testClient).toBeTruthy();
});

tap.test('create a new machine user', async () => {
  const machineUser = await testCloudly.authManager.CUser.createMachineUser('test', 'api');
  machineUser.data.tokens.push({
    token: 'test',
    expiresAt: Date.now() + 3600 * 1000 * 24 * 365,
    assignedRoles: ['api'],
  })
  await machineUser.save();
})

tap.test('should get an identity', async () => {
  const identity = await testClient.getIdentityByToken('test');
  expect(identity).toBeTruthy();
  console.log(identity);
});

let image: Image;
tap.test('should create and upload an image', async () => {
  image = await testClient.image.createImage({
    name: 'test',
    description: 'test'
  });
  console.log('created image: ', image);
  expect(image).toBeInstanceOf(Image);
})

tap.test('should upload an image version', async () => {
  const imageStream = await helpers.getAlpineImageReadableStream();

  await image.pushImageVersion('v1.0.0', imageStream);
});

tap.test('should stop the apiclient', async (toolsArg) => {
  await toolsArg.delayFor(10000);
  await helpers.stopCloudly();
  await testClient.stop();
  await testCloudly.stop();
})

export default tap.start();