const githubChangelog = require('@changesets/changelog-github')

function stripMetadata(summary) {
  return summary
    .replace(/^\s*(?:pr|pull|pull\s+request):\s*#?(\d+)/gim, '')
    .replace(/^\s*commit:\s*(\S+)/gim, '')
    .replace(/^\s*(?:author|user):\s*@?(\S+)/gim, '')
    .trim()
}

function toBullet(summary) {
  const cleaned = stripMetadata(summary)
  const [firstLine, ...futureLines] = cleaned.split('\n').map(line => line.trimEnd())
  return `\n\n- ${firstLine}\n${futureLines.map(line => `  ${line}`).join('\n')}`.trimEnd()
}

module.exports = {
  getDependencyReleaseLine: async (changesets, dependenciesUpdated, options) => {
    try {
      return await githubChangelog.getDependencyReleaseLine(changesets, dependenciesUpdated, options)
    }
    catch {
      if (dependenciesUpdated.length === 0) {
        return ''
      }

      return ['- Updated dependencies:', ...dependenciesUpdated.map(dependency => `  - ${dependency.name}@${dependency.newVersion}`)].join('\n')
    }
  },
  getReleaseLine: async (changeset, type, options) => {
    try {
      return await githubChangelog.getReleaseLine(changeset, type, options)
    }
    catch {
      return toBullet(changeset.summary)
    }
  },
}
