import { Buffer } from 'node:buffer'
import { createNodeMiddleware } from '@octokit/webhooks'
import consola from 'consola'
import { BotServer } from '../hono'
import { createOctokitWebhooks } from './octokit'
import { WebhooksOptions } from './types'

// import * as octokit from '@octokit/webhooks'
// import { githubHandler } from './github-handler'
import colors from 'picocolors'

export * from './types'

/**
 * create webhook
 * - github
 * @param app
 */
export function createWebhooks(app: BotServer, options: WebhooksOptions) {
  const path = options.octokit.middlewareOptions?.path || '/api/github/webhooks'
  consola.success(`🪝  Webhooks enabled at ${colors.green(`http://localhost:${options.port}${path}`)}`)

  const webhooks = createOctokitWebhooks({
    secret: options.octokit.secret,
  })
  webhooks.onAny(({ id, name, payload }) => {
    consola.info(`🪝  ${colors.green(name)} event received: ${colors.green(id)}`)
    // eslint-disable-next-line no-console
    console.dir(payload)
  })

  /**
   * ref https://github.com/octokit/webhooks.js/blob/b22596fe031aa89873ba7bad0ff4329c0b882832/test/integration/node-middleware.test.ts#L73
   */
  const dataChunks: any[] = []
  const middleware = createNodeMiddleware(webhooks, options.octokit.middlewareOptions)
  app.use(async (ctx, next) => {
    const req = ctx.env.incoming
    const res = ctx.env.outgoing
    req.once('data', chunk => dataChunks.push(chunk))
    req.once('end', () => {
      // @ts-expect-error - TS2339: Property 'body' does not exist on type 'IncomingMessage'.
      req.body = Buffer.concat(dataChunks).toString()
      middleware(req, res)
    })
    await next()
  })
}
