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

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

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

    const message =
      `🙌 New contact request\n` +
      `👤 Name: ${data.firstName}\n` +
      `✉️ Email: ${data.email}\n` +
      (data.phone ? `📱 Phone: ${data.phone}\n` : '') +
      `💬 Message: ${data.content}`;

    const url = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage?chat_id=${TELEGRAM_CHAT_ID}&parse_mode=HTML&text=${encodeURIComponent(message)}`;
    const tgResponse = await fetch(url);
    const tgJson = await tgResponse.json();
    console.log('Telegram response:', tgJson);

    if (!tgResponse.ok) {
      return NextResponse.json({ ok: false, error: tgJson }, { status: 500 });
    }

    return NextResponse.json({ ok: true, telegram: tgJson });
  } catch (e) {
    console.error('Telegram API error:', e);
    return NextResponse.json({ ok: false, error: 'Server error' }, { status: 500 });
  }
}
