import { NextResponse } from "next/server";
import axios from "axios";

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

    // Validation
    if (!phone || typeof phone !== "string" || phone.trim() === "") {
      return NextResponse.json(
        { error: "Phone number is required" },
        { status: 400 }
      );
    }

    // Get Telegram credentials from environment
    const token = process.env.TELEGRAM_BOT_TOKEN;
    const chatId = process.env.TELEGRAM_CHAT_ID;

    if (!token || !chatId) {
      console.error("Telegram credentials not configured");
      return NextResponse.json(
        { error: "Server not properly configured" },
        { status: 500 }
      );
    }

    // Format message for Telegram
    const telegramMessage = `
📨 New Contact Message

👤 Name: ${name || "—"}
📱 Phone: ${phone}
📝 Message: ${message || "—"}
🔧 Product: ${productSlug || "—"}
🌐 Language: ${lang || "—"}

---
Sent from firma.uz
    `.trim();

    // Send to Telegram
    try {
      await axios.post(
        `https://api.telegram.org/bot${token}/sendMessage`,
        {
          chat_id: chatId,
          text: telegramMessage,
          parse_mode: "HTML",
        },
        {
          timeout: 10000,
        }
      );

      return NextResponse.json(
        {
          ok: true,
          message: "Message sent successfully",
        },
        { status: 200 }
      );
    } catch (telegramError) {
      console.error("Telegram API error:", telegramError);
      return NextResponse.json(
        { error: "Failed to send message via Telegram" },
        { status: 500 }
      );
    }
  } catch (error) {
    console.error("Contact API error:", error);
    return NextResponse.json({ error: "Invalid request" }, { status: 400 });
  }
}
