import { NOTIFICATION_EVENTS } from '../../../shared/constants/notification-events.js'
import { prisma } from '../lib/prisma.js'
import { validateWebhook } from '../lib/yookassa.js'

export async function registerYookassaWebhookRoute(fastify) {
  fastify.post('/api/webhooks/yookassa', async (request, reply) => {
    let body
    try {
      body = typeof request.body === 'string' ? JSON.parse(request.body) : request.body
    } catch (err) {
      request.log.error({ err }, 'Failed to parse webhook JSON body')
      return reply.code(400).send({ error: 'Invalid JSON body' })
    }

    let event, paymentObject
    try {
      const clientIp = request.ip
      ;({ event, paymentObject } = validateWebhook(clientIp, body))
    } catch (err) {
      return reply.code(400).send({ error: err.message })
    }

    const yookassaPaymentId = paymentObject.id
    if (!yookassaPaymentId) {
      return reply.code(400).send({ error: 'Missing payment id in webhook object' })
    }

    const payment = await prisma.payment.findFirst({
      where: { yookassaPaymentId },
    })
    if (!payment) {
      return reply.code(404).send({ error: 'Payment not found' })
    }

    await prisma.payment.update({
      where: { id: payment.id },
      data: { status: paymentObject.status },
    })

    if (event === 'payment.succeeded') {
      const order = await prisma.order.findFirst({
        where: { id: payment.orderId },
      })
      if (order && order.status === 'PENDING_PAYMENT') {
        const updated = await prisma.order.updateMany({
          where: { id: payment.orderId, status: 'PENDING_PAYMENT' },
          data: { status: 'PAID' },
        })
        if (updated.count > 0) {
          fastify.eventBus.emit(NOTIFICATION_EVENTS.PAYMENT_STATUS_CHANGED, {
            orderId: payment.orderId,
            userId: order.userId,
            paymentStatus: 'paid',
          })
        }
      }
    }

    return { ok: true }
  })
}
