import { NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { getLatestEmail } from '@/lib/mail'; import { sendTelegramNotification } from '@/lib/notifications'; // Bu kısım normalde .env içinde olmalı const WEBHOOK_SECRET = 'besiktasK1903*'; const IMAP_PASSWORD = process.env.MAILCOW_MASTER_PASSWORD || ''; // Dovecot Master Password tavsiye edilir export async function POST(request: Request) { const secret = request.headers.get('x-ayristech-secret'); if (secret !== WEBHOOK_SECRET) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const body = await request.json(); const { to, event, timestamp } = body; console.log(`📩 Webhook Sinyali Alındı! Alıcı: ${to}`); try { // 1. Mailbox Mapping kontrolü const mapping = await prisma.mailboxMapping.findUnique({ where: { email: to }, include: { user: true } }); if (!mapping) { console.log(`[Signal] Mapping bulunamadı: ${to}`); return NextResponse.json({ success: true, message: 'No mapping found' }); } // 2. Mailcow'dan son maili çek // Not: Master password kullanılıyorsa format 'user@domain.tld*master@domain.tld' şeklindedir const loginUser = IMAP_PASSWORD ? `${to}*${process.env.MAILCOW_MASTER_USER || 'admin'}` : to; const mailData = await getLatestEmail(to, IMAP_PASSWORD); if (!mailData) { console.error(`[Signal] Mail içeriği çekilemedi: ${to}`); return NextResponse.json({ success: false, error: 'Could not fetch mail' }, { status: 500 }); } console.log(`[Signal] Mail Çekildi: "${mailData.subject}"`); // 3. İçerik Analizi (BMW, Penti vb.) let processed = false; let extraInfo = ""; const content = (mailData.subject + " " + mailData.text).toLowerCase(); if (content.includes("bmw") || content.includes("tamir")) { console.log("🚗 [Signal] BMW/Tamir içerikli mail tespit edildi!"); extraInfo = "🚗 BMW/Tamir İlgili İçerik"; processed = true; } if (content.includes("penti") || content.includes("sipariş")) { console.log("🛍️ [Signal] Penti/Sipariş içerikli mail tespit edildi!"); extraInfo = "🛍️ Penti/Sipariş İlgili İçerik"; processed = true; } // 4. Bildirim Gönder (Telegram) const notificationResult = await sendTelegramNotification( mapping.userId, to, mailData.from, mailData.subject, extraInfo ); // 5. Bildirim Logu await prisma.notificationLog.create({ data: { mailbox: to, sender: mailData.from, subject: mailData.subject, status: notificationResult.status, userId: mapping.userId, error: notificationResult.error || (processed ? null : "Anahtar kelime eşleşmedi") } }); return NextResponse.json({ success: true, processed, notification: notificationResult.status, subject: mailData.subject }); } catch (error: any) { console.error("[Signal Webhook] Hata:", error.message); return NextResponse.json({ error: error.message }, { status: 500 }); } }