const fs = require('fs').promises

const Config = require('./index')

let jsonDefaults = {
  setting:"defaultvalue",
  another: {
    setting:"avalue"
  }
}

let jsonLocals = {
  setting:"localvalue",
  another: {
    more:"stuff"
  },
  even: {
    deeper: {
      key: 'sodeep'
    }
  }
}

describe('config', function() {

  it('should only have values from config.defaults.json', async function() {
    await fs.writeFile('config.defaults.json', JSON.stringify(jsonDefaults))
    let config = new Config()
    await fs.unlink('config.defaults.json')

    expect(config.setting).toBe('defaultvalue')
    expect(config.another.setting).toBe('avalue')
  })

  it('should only have values from config.json', async function() {
    await fs.writeFile('config.json', JSON.stringify(jsonLocals))
    let config = new Config()
    await fs.unlink('config.json')

    expect(config.setting).toBe('localvalue')
    expect(config.another.more).toBe('stuff')
  })

  it('should have both values with preference to config.json', async function() {
    await fs.writeFile('config.defaults.json', JSON.stringify(jsonDefaults))
    await fs.writeFile('config.json', JSON.stringify(jsonLocals))
    let config = new Config()
    await fs.unlink('config.json')
    await fs.unlink('config.defaults.json')

    expect(config.setting).toBe('localvalue')
    expect(config.another.more).toBe('stuff')
    expect(config.another.setting).toBe('avalue')
  })

  it('should have all values with preference to env', async function() {
    await fs.writeFile('config.defaults.json', JSON.stringify(jsonDefaults))
    await fs.writeFile('config.json', JSON.stringify(jsonLocals))
    
    process.env['SETTING'] = 'overwritten-by-env'
    process.env['ANOTHER_MORE'] = 'overwritten-by-env2'
    process.env['EVEN_DEEPER_KEY'] = 'overwritten-by-env3'
    
    let config = new Config()

    await fs.unlink('config.json')
    await fs.unlink('config.defaults.json')

    expect(config.setting).toBe('overwritten-by-env')
    expect(config.another.more).toBe('overwritten-by-env2')
    expect(config.even.deeper.key).toBe('overwritten-by-env3')
    expect(config.another.setting).toBe('avalue')
  })
})