import { prisma } from '../../../lib/prisma.js'

export async function registerAdminNotificationRoutes(fastify) {
  fastify.get('/api/admin/notifications/settings', { preHandler: [fastify.verifyAdmin] }, async () => {
    let settings = await prisma.adminNotificationSettings.findFirst()
    if (!settings) {
      settings = await prisma.adminNotificationSettings.create({
        data: {
          emailEnabled: true,
          telegramEnabled: false,
          newOrder: true,
          newOrderMessage: true,
          newReview: true,
          authCodeDuplicate: false,
        },
      })
    }
    return { settings }
  })

  fastify.put('/api/admin/notifications/settings', { preHandler: [fastify.verifyAdmin] }, async (request) => {
    const body = request.body || {}
    let settings = await prisma.adminNotificationSettings.findFirst()

    const data = {}
    if ('emailEnabled' in body) data.emailEnabled = Boolean(body.emailEnabled)
    if ('telegramEnabled' in body) data.telegramEnabled = Boolean(body.telegramEnabled)
    if ('telegramChatId' in body) data.telegramChatId = body.telegramChatId || null
    if ('newOrder' in body) data.newOrder = Boolean(body.newOrder)
    if ('newOrderMessage' in body) data.newOrderMessage = Boolean(body.newOrderMessage)
    if ('newReview' in body) data.newReview = Boolean(body.newReview)
    if ('authCodeDuplicate' in body) data.authCodeDuplicate = Boolean(body.authCodeDuplicate)

    if (!settings) {
      settings = await prisma.adminNotificationSettings.create({ data })
    } else {
      settings = await prisma.adminNotificationSettings.update({
        where: { id: settings.id },
        data,
      })
    }

    return { settings }
  })

  fastify.post('/api/admin/notifications/telegram/webhook', async (request) => {
    const update = request.body || {}
    const message = update.message
    if (!message || !message.text || message.text !== '/start') return { ok: true }

    const chatId = String(message.chat.id)
    const settings = await prisma.adminNotificationSettings.findFirst()

    if (settings) {
      await prisma.adminNotificationSettings.update({
        where: { id: settings.id },
        data: { telegramChatId: chatId },
      })
    } else {
      await prisma.adminNotificationSettings.create({
        data: { telegramChatId: chatId },
      })
    }

    if (process.env.TELEGRAM_BOT_TOKEN) {
      await fetch(`https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/sendMessage`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          chat_id: chatId,
          text: 'Вы подписаны на уведомления Любимый Креатив.',
        }),
      })
    }

    return { ok: true }
  })
}
