'use strict'

const cli = require('heroku-cli-util')
const { sortBy } = require('lodash')
const util = require('../lib/util')

async function run(context, heroku) {
  const fetcher = require('../lib/fetcher')(heroku)

  const { app, args, flags } = context

  let showCredentials = async function () {
    const host = require('../lib/host')
    let addon = await fetcher.addon(app, args.database)
    let attachments = []
    let credentials = []

    function presentCredential (cred) {
      let credAttachments = []
      if (cred !== 'default') {
        credAttachments = attachments.filter(a => a.namespace === `credential:${cred}`)
      } else {
        credAttachments = attachments.filter(a => a.namespace === null)
      }
      return util.presentCredentialAttachments(app, credAttachments, credentials, cred)
    }

    credentials = await heroku.get(`/postgres/v0/databases/${addon.name}/credentials`,
      { host: host(addon) })
    let isDefaultCredential = (cred) => cred.name !== 'default'
    credentials = sortBy(credentials, isDefaultCredential, 'name')
    attachments = await heroku.get(`/addons/${addon.name}/addon-attachments`)

    cli.warn(`${cli.color.cmd('pg:credentials')} has recently changed. Please use ${cli.color.cmd('pg:credentials:url')} for the previous output.`)
    cli.table(credentials, {
      columns: [
        { key: 'name', label: 'Credential', format: presentCredential },
        { key: 'state', label: 'State' }
      ]
    })
  }

  if (flags.reset) {
    cli.error(`${cli.color.cmd('pg:credentials --reset')} is deprecated. Please use ${cli.color.cmd('pg:credentials:rotate')} instead.`)
  } else {
    await showCredentials()
  }
}

module.exports = {
  topic: 'pg',
  command: 'credentials',
  description: 'show information on credentials in the database',
  needsApp: true,
  needsAuth: true,
  flags: [{ name: 'reset', description: 'DEPRECATED' }],
  args: [{ name: 'database', optional: true }],
  run: cli.command({ preauth: true }, run)
}

@@ -1481,179 +1481,8 @@
  %7D%0A%0A
-  if (flags.reset) %7B%0A    cli.error(%60$%7Bcli.color.cmd('pg:credentials --reset')%7D is deprecated. Please use $%7Bcli.color.cmd('pg:credentials:rotate')%7D instead.%60)%0A  %7D else %7B%0A  
   aw
@@ -1503,20 +1503,16 @@
 tials()%0A
-  %7D%0A
 %7D%0A%0Amodul
@@ -1650,16 +1650,16 @@
 : true,%0A
+
   needsA
@@ -1673,65 +1673,8 @@
 ue,%0A
-  flags: %5B%7B name: 'reset', description: 'DEPRECATED' %7D%5D,%0A
   ar

remove reset flag from pg:credentials (#1898)