/**
 * Manage staff ChatGPT sessions (AUTH_MODE=magento).
 *   pnpm auth:sessions            list users with live sessions
 *   pnpm auth:revoke <username>   sign a Magento admin out of every connected client now
 */
import { createDb, listOAuthSessions, revokeOAuthSubject } from '@znet/catalog-db'
import { baseEnv, databaseEnv, loadEnv } from '@znet/shared'

const env = loadEnv(baseEnv.extend(databaseEnv.shape))
const { db, close } = createDb(env.DATABASE_URL, { max: 1 })
const [command, username] = process.argv.slice(2)

try {
  if (command === 'sessions') {
    console.table([...(await listOAuthSessions(db))])
  } else if (command === 'revoke' && username) {
    console.log(`revoked ${await revokeOAuthSubject(db, username.toLowerCase())} token(s) for ${username}`)
  } else {
    console.error('usage: auth:sessions | auth:revoke <username>')
    process.exitCode = 2
  }
} finally {
  await close()
}
