import * as fs from 'fs'
import * as path from 'path'

const COMMON_MOCK = {
  projectPath: jest.fn(),
  sureLazyImport: jest.fn(),

  TIMPLA_PROCESS: {
    TIMPLA_DIR: 'TIMPLA_DIR',
  },
}

beforeEach(() => {
  jest.resetModules()
})

describe('resolveConfig', () => {
  it('should resolve the specified timpla config', () => {
    jest.mock('../../gulpfile.ts/internal', () => ({
      ...COMMON_MOCK,
      TIMPLA_PROCESS: {
        INIT_CWD: 'INIT_CWD',
        TIMPLA_CONFIG_FILE: 'TIMPLA_CONFIG_FILE',
        TIMPLA_DIR: 'TIMPLA_DIR',
      },
      projectPath: jest.fn().mockReturnValue('SPECIFIED_FILE'),
    }))
    const { resolveConfig } = require('../../gulpfile.ts/lib/TIMPLA_CONFIG')
    const result = resolveConfig()
    expect(result).toEqual('SPECIFIED_FILE')
  })
  it("should resolve to the user's config", () => {
    jest.mock('../../gulpfile.ts/internal', () => ({
      ...COMMON_MOCK,
      TIMPLA_PROCESS: {
        INIT_CWD: 'INIT_CWD',
        TIMPLA_DIR: 'TIMPLA_DIR',
      },
      projectPath: jest.fn().mockReturnValue('USER_CONFIG'),
    }))
    jest.spyOn(fs, 'existsSync').mockReturnValueOnce(true)
    const { resolveConfig } = require('../../gulpfile.ts/lib/TIMPLA_CONFIG')
    const result = resolveConfig()
    expect(result).toEqual('USER_CONFIG')
  })
  it('should resolve to the default config', () => {
    jest.mock('path', () => ({
      resolve: jest.fn().mockReturnValueOnce('DEFAULT_CONFIG'),
    }))
    jest.mock('../../gulpfile.ts/internal', () => ({
      ...COMMON_MOCK,
      TIMPLA_PROCESS: {
        INIT_CWD: 'INIT_CWD',
        TIMPLA_DIR: 'TIMPLA_DIR',
      },
    }))
    jest.spyOn(fs, 'existsSync').mockReturnValueOnce(false)
    const { resolveConfig } = require('../../gulpfile.ts/lib/TIMPLA_CONFIG')
    const result = resolveConfig()
    expect(result).toEqual('DEFAULT_CONFIG')
  })
})

describe('TIMPLA_CONFIG', () => {
  it('should be loaded from the resolved config', () => {
    jest.mock('../../gulpfile.ts/internal')
    const internal = require('../../gulpfile.ts/internal')
    const spyLazy = jest.spyOn(internal, 'sureLazyImport').mockReturnValue({ hello: 1 })
    const { TIMPLA_CONFIG, resolveConfig } = require('../../gulpfile.ts/lib/TIMPLA_CONFIG')
    expect(spyLazy).toHaveBeenCalledWith(resolveConfig())
    expect(TIMPLA_CONFIG).toMatchObject({ hello: 1 })
  })
})
