import { NextRequest, NextResponse } from 'next/server';
interface EventData {
name: string;
phone: string;
guests: string;
date: string;
time: string;
info: string;
eventType: string;
}
const formattedDate = (date: string) => {
const [year, month, day] = date.split('-');
const dateObj = new Date(+year, +month - 1, +day);
const months = [
'яну',
'фев',
'март',
'апр',
'май',
'юни',
'юли',
'авг',
'септ',
'окт',
'ноем',
'дек'
];
const monthName = months[dateObj.getMonth()];
const dayName = dateObj.toLocaleString('bg-BG', { weekday: 'short' });
return `${dayName}, ${day} ${monthName}`;
};
export async function POST(req: NextRequest) {
try {
const webhookUrl = process.env.DISCORD_WEBHOOK_URL;
// Handle the case where webhookUrl is not set
if (!webhookUrl) {
console.error('Discord webhook URL is not set in environment variables.');
return NextResponse.json(
{ message: 'Server error: Discord webhook URL is not configured.' },
{ status: 500 }
);
}
const data: EventData = await req.json();
// Validate required fields
const { name, phone, guests, date, time, info, eventType } = data;
if (!phone || !date || !time) {
return NextResponse.json(
{ message: 'Bad request: Missing required event data.' },
{ status: 400 }
);
}
// Construct the plain text message content
const messageContent = {
username: 'Reservation Bot',
avatar_url: 'https://www.vkashti.bar/logo.png',
content: `
**${name || 'Анонимен'} направи резервация за ${guests} гости за ${formattedDate(date)} в ${time} часа.**
${phone ?? 'Без номер'} | ${info || 'Без информация'} | ${eventType}
-# Дай peeking face, за да видиш резервациите на този ден. 🫣
-# Дай палец нагоре, ако е ок. 👍
-# Ще пратя СМС на клиента и ще добавя резервацията в календара. 📅
`
};
// Send the message to Discord via the webhook
const discordResponse = await fetch(webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(messageContent)
});
if (!discordResponse.ok) {
console.error(
'Failed to send message to Discord webhook:',
discordResponse.statusText
);
return NextResponse.json(
{ message: 'Error sending message to Discord.' },
{ status: 500 }
);
}
return NextResponse.json({ message: 'Success' }, { status: 200 });
} catch (error) {
console.error('Error:', error);
return NextResponse.json({ message: 'Server error.' }, { status: 500 });
}
}