import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'

export async function POST(req: NextRequest) {
  try {
    const { email } = await req.json()

    if (!email) {
      return NextResponse.json({ message: 'Email is required' }, { status: 400 })
    }

    const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN as string
    const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID as string

    const telegramApiUrl = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`
    const text = `New subscription!\nEmail: ${email}`

    const tgRes = await fetch(telegramApiUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        chat_id: TELEGRAM_CHAT_ID,
        text,
      }),
    })

    if (!tgRes.ok) {
      return NextResponse.json({ message: 'Ошибка отправки в Telegram' }, { status: 500 })
    }

    return NextResponse.json({ message: 'Отправлено!' }, { status: 200 })
  } catch (e) {
    return NextResponse.json({ message: 'Ошибка сервера', error: String(e) }, { status: 500 })
  }
}
