const { requireValue }  = require( './services/utils')

const fetch  = require( 'node-fetch').default

const getVersion = require( './services/version')

module.exports = async (options, logger) => {

  const versionInfo = await getVersion(options, logger)

  let {
    project = process.env.PROJECT_ID || requireValue('project'),
    version = process.env.VERSION || versionInfo.version || requireValue( 'version' ),
    component = process.env.COMPONENT || false,
    jira_release_hook_component = process.env.JIRA_RELEASE_HOOK_COMPONENT || 'https://automation.atlassian.com/pro/hooks/16225ebd0ca5e49d465cd121ae4d4fecb684bd2f',
    jira_release_hook_project = process.env.JIRA_RELEASE_HOOK_PROJECT || 'https://automation.atlassian.com/pro/hooks/babff4335c2ecb135235f32bbc34d1dc56e228c9'
  } = options


  await fetch(component ? jira_release_hook_component : jira_release_hook_project, {
    method: 'POST',
    body: JSON.stringify({
      releaseVersion: version,
      projectId: project,
      component: component
    }),
    headers: {'Content-Type': 'application/json'}
  })

  logger(`Released version "${version}" sent to Jira project ${project.toUpperCase()} ${component ? component : ''}`.green)
  return 0
}
