import { stub } from 'eltro'
import { ServiceCore } from 'service-core'
import Client from './helper.client.mjs'
import defaults from '../api/defaults.mjs'
import * as index from '../index.mjs'

export const port = 5030

export const log = {
  log: stub(),
  warn: stub(),
  info: stub(),
  error: stub(),
  child: stub(),
  event: {
    warn: stub(),
    info: stub(),
    error: stub(),
  }
}
log.child.returns(log)

let serverRunning = false

export function startServer() {
  if (serverRunning) return Promise.resolve()
  serverRunning = true

  var core = new ServiceCore('storage-upload', import.meta.url, port, '')
  core.setConfig({
    "port": port,
    "sites": {
      "development": {
        "keys": {
          "default@HS256": "asdf1234"
        }
      },
      "existing": {
        "public": true,
        "keys": {
          "default@HS256": "asdf1234"
        }
      }
    },
  })

  core.log = log

  return core.init(index).then(function() {
    return core.run()
  })
}


export function createClient() {
  return new Client(port)
}

export function resetLog() {
  log.log.reset()
  log.info.reset()
  log.warn.reset()
  log.error.reset()
}

export function createContext(opts) {
  return defaults(opts, {
    query: new Map(),
    params: { },
    req: { },
    res: { },
    state: {},
    log: {
      log: stub(),
      warn: stub(),
      info: stub(),
      error: stub(),
    },
  })
}
