import { NextRequest, NextResponse } from 'next/server' const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ // Basit in-memory rate limiting const ipRequestMap = new Map() const RATE_LIMIT = 5 // maksimum istek const WINDOW_MS = 60_000 // 1 dakika function checkRateLimit(ip: string): boolean { const now = Date.now() const entry = ipRequestMap.get(ip) if (!entry || now > entry.resetAt) { ipRequestMap.set(ip, { count: 1, resetAt: now + WINDOW_MS }) return true } if (entry.count >= RATE_LIMIT) return false entry.count++ return true } function escapeHtml(str: string): string { return str .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') } async function sendTelegramNotification({ name, email, org, phone, ip, }: { name: string email: string org?: string | null phone?: string | null ip: string }) { const botToken = process.env.TELEGRAM_BOT_TOKEN const chatId = process.env.TELEGRAM_CHAT_ID if (!botToken || !chatId) { console.warn('[AyrisLegal] Telegram bildirim ayarları eksik (TELEGRAM_BOT_TOKEN veya TELEGRAM_CHAT_ID ortam değişkeni tanımlanmamış).') return } const now = new Date().toLocaleString('tr-TR', { timeZone: 'Europe/Istanbul' }) const text = `⚖️ [AyrisLegal] Yeni Demo & İletişim Talebi\n\n` + `📍 Kaynak: ayrislegal.com / İletişim Formu\n` + `👤 Ad Soyad: ${escapeHtml(name)}\n` + `📧 E-posta: ${escapeHtml(email)}\n` + `🏢 Büro / Kurum: ${org ? escapeHtml(org) : 'Belirtilmedi'}\n` + `📞 Telefon: ${phone ? `${escapeHtml(phone)}` : 'Belirtilmedi'}\n` + `🌐 IP Adresi: ${escapeHtml(ip)}\n` + `⏰ Tarih: ${now}\n\n` + `Bu mesaj AyrisLegal web sitesinden gönderilmiştir.` try { const res = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chat_id: chatId, text, parse_mode: 'HTML', disable_web_page_preview: true, }), }) if (!res.ok) { const errText = await res.text() console.error('[AyrisLegal] Telegram API yanıt hatası:', errText) } else { console.log('[AyrisLegal] ✅ Telegram bildirimi başarıyla iletildi.') } } catch (error) { console.error('[AyrisLegal] Telegram gönderim hatası:', error) } } export async function POST(request: NextRequest) { try { // IP tespiti const forwarded = request.headers.get('x-forwarded-for') const ip = forwarded ? forwarded.split(',')[0].trim() : 'unknown' // Rate limit if (!checkRateLimit(ip)) { return NextResponse.json( { success: false, error: 'Çok fazla istek gönderildi. Lütfen bir dakika bekleyip tekrar deneyin.' }, { status: 429 } ) } const body = await request.json() const { name, email, org, phone, barNo, message, _hp } = body // Honeypot kontrolü (Bot engelleme) if (_hp) { return NextResponse.json({ success: true }) } // Zorunlu alan doğrulaması if (!name || typeof name !== 'string' || name.trim().length < 2) { return NextResponse.json( { success: false, error: 'Lütfen ad ve soyadınızı belirtin (en az 2 karakter).' }, { status: 400 } ) } if (!email || typeof email !== 'string' || !EMAIL_REGEX.test(email.trim())) { return NextResponse.json( { success: false, error: 'Lütfen geçerli bir e-posta adresi girin.' }, { status: 400 } ) } const leadData = { name: name.trim(), email: email.trim().toLowerCase(), org: org?.trim() || barNo?.trim() || null, phone: phone?.trim() || message?.trim() || null, ip, } // Konsol logu console.log('[AyrisLegal] 🎯 Yeni Demo Talebi Alındı:', { timestamp: new Date().toISOString(), ...leadData, }) // Telegram Botuna Anlık Bildirim Gönder (Hata durumunda form akışını kesmez) await sendTelegramNotification(leadData) return NextResponse.json({ success: true }, { status: 200 }) } catch (err) { console.error('[AyrisLegal] Contact API hatası:', err) return NextResponse.json( { success: false, error: 'Sunucu hatası oluştu. Lütfen tekrar deneyin.' }, { status: 500 } ) } }