import { NextResponse } from 'next/server';

export async function POST(req: Request) {
  const body = await req.json();
  const { name, phone } = body;

  const BOT_TOKEN = process.env.BOT_TOKEN;
  const CHAT_IDS = process.env.BOT_CHAT_IDS?.split(',') || [];

  if (!BOT_TOKEN || CHAT_IDS.length === 0) {
    return NextResponse.json(
      { success: false, message: 'Server not configured properly' },
      { status: 500 },
    );
  }

  const text = `
📩 *Новая заявка на обратный звонок*

👤 *Имя:* _${name}_
📞 *Телефон:* _${phone}_
`;

  const sendMessage = async (chatId: string) => {
    return fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ chat_id: chatId, text, parse_mode: 'Markdown' }),
    });
  };

  const results = await Promise.allSettled(
    CHAT_IDS.map((id) => sendMessage(id)),
  );

  const hasSuccess = results.some((r) => r.status === 'fulfilled');

  if (!hasSuccess) {
    return NextResponse.json(
      { success: false, message: 'Telegram error' },
      { status: 500 },
    );
  }

  return NextResponse.json({ success: true });
}
