import { Eltro as t, assert, stub } from 'eltro'
import fs from 'fs/promises'
import Application from '../core/application.mjs'
import GitProvider from '../core/providers/git.mjs'
import Util from '../core/util.mjs'
import { createFakeContext } from './helpers.mjs'

const util = new Util(import.meta.url)
let ctx
let app
let provider

t.before(function() {
  return createFakeContext({ }, util, util.getPathFromRoot('./db_test.json'))
    .then(function(res) {
      ctx = res
      provider = new GitProvider({ url: 'https://git.nfp.is/api/v1/repos/thething/sc-helloworld/releases' })
      app = new Application(ctx, provider, 'testapp')

      return provider.getLatestVersion()
    }).then(function(version) {
      return fs.rm(`./test/testapp/${version.version}`, { force: true, recursive: true })
    })
})

t.after(function() {
  return fs.rm(util.getPathFromRoot('./db_test.json'))
    .then(function() {
      if (ctx.db.data.core.testapp.versions.length) {
        return fs.rm(`./test/testapp/${ctx.db.data.core.testapp.versions[0].id}`, { force: true, recursive: true })
      }
    })
})

t.skip().timeout(10000).test('should run update and install correctly', async function(){
  try {
    await app.update()
  } catch (err) {
    console.log()
    console.log(err)
    if (ctx.db.data.core.testapp.versions.length) {
      console.log(ctx.db.data.core.testapp.versions[0].log)
    }
    throw err
  }

  assert.ok(ctx.db.data.core.testapp.latestInstalled)
  await fs.stat(util.getPathFromRoot(`./testapp/${ctx.db.data.core.testapp.latestInstalled}/index.mjs`))
  await fs.stat(util.getPathFromRoot(`./testapp/${ctx.db.data.core.testapp.latestInstalled}/package.json`))
  await fs.stat(util.getPathFromRoot(`./testapp/${ctx.db.data.core.testapp.latestInstalled}/node_modules`))
})
