import { Airgram, Auth, prompt, toObject } from 'airgram'
import dotenv from 'dotenv'

dotenv.config()
console.log(process.env)

const airgram = new Airgram({
  apiId: process.env.APP_ID,
  apiHash: process.env.APP_HASH
})

airgram.use(new Auth({
  code: () => prompt(`Please enter the secret code:\n`),
  phoneNumber: () => prompt(`Please enter your phone number:\n`)
}))

void (async () => {
  const me = toObject(await airgram.api.getMe())
  console.log(`[me]`, me)
})

// Getting all updates
airgram.use((ctx, next) => {
  if ('update' in ctx) {
    console.log(`[all updates][${ctx._}]`, JSON.stringify(ctx.update))
  }
  return next()
})

// Getting new messages
airgram.on('updateNewMessage', async ({ update }, next) => {
  const { message } = update
  console.log('[new message]', message)
  return next()
})
