import { Eltro as t, assert, stub } from 'eltro'
import * as sc from '../index.mjs'

t.describe('', function() {
  const module = {
    start: stub()
  }

  t.beforeEach(function() {
    module.start.reset()
  })

  t.test('should have ServiceCore defined', function() {
    assert.ok(sc.ServiceCore)
  })

  t.test('constructor should work', function() {
    const assertAppName = 'Gondola'
    let core = new sc.ServiceCore(assertAppName, import.meta.url)
    assert.strictEqual(core.util._root_import_meta_url, import.meta.url)
    assert.strictEqual(core.name, assertAppName)
  })

  t.test('should support proper init', async function() {
    const assertAppName = 'Hero Combat'
    let core = new sc.ServiceCore(assertAppName, import.meta.url)
    await core.init(module)

    assert.strictEqual(core.core.applications.length, 1)
    assert.strictEqual(core.core.applications[0], core.app)
    assert.strictEqual(core.core.applicationMap.size, 1)
    assert.strictEqual(core.core.applicationMap.get(assertAppName), core.app)
    assert.strictEqual(core.app.name, assertAppName)
    assert.strictEqual(core.app.module, module)
  })

  t.test('should call module start', async function() {
    const assertError = new Error('Inbo')
    module.start.rejects(assertError)
    
    let core = new sc.ServiceCore('testapp', import.meta.url)
    await core.init(module)
    let err = await assert.isRejected(core.run())
    assert.strictEqual(err, assertError)
    assert.strictEqual(module.start.firstCall[0], core.app.http)
    assert.strictEqual(module.start.firstCall[1], 4000)
    assert.strictEqual(module.start.firstCall[2], core.app.ctx)
  })

  t.test('should support overwriting port', async function() {
    const assertError = new Error('Inbo')
    const assertPort = 9382
    module.start.rejects(assertError)
    
    let core = new sc.ServiceCore('testapp', import.meta.url, assertPort)

    await core.init(module)
    
    let err = await assert.isRejected(core.run())
    assert.strictEqual(err, assertError)
    assert.strictEqual(module.start.firstCall[0], core.app.http)
    assert.strictEqual(module.start.firstCall[1], assertPort)
    assert.strictEqual(module.start.firstCall[2], core.app.ctx)
  })

  t.test('should support overwriting config', async function() {
    const assertError = new Error('Inbo')
    const assertPort = 9382
    module.start.rejects(assertError)
    
    let core = new sc.ServiceCore('testapp', import.meta.url)

    core.setConfig({
      port: assertPort
    })
    await core.init(module)
    
    let err = await assert.isRejected(core.run())
    assert.strictEqual(err, assertError)
    assert.strictEqual(core.config['testapp'].port, assertPort)
    assert.strictEqual(core.config['testapp'].provider, 'static')
    assert.strictEqual(module.start.firstCall[0], core.app.http)
    assert.strictEqual(module.start.firstCall[1], assertPort)
    assert.strictEqual(module.start.firstCall[2], core.app.ctx)
  })
})
