
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { sendEmailNotification } from '@/lib/email'
import { sendTelegramNotification } from '@/lib/telegram'

export const dynamic = "force-dynamic"

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { name, phone, email, serviceType, message } = body

    // Basic validation
    if (!name || !phone) {
      return NextResponse.json(
        { error: 'Имя и телефон обязательны для заполнения' },
        { status: 400 }
      )
    }

    // Prepare data
    const submissionData = {
      name: name.trim(),
      phone: phone.trim(),
      email: email?.trim() || null,
      serviceType: serviceType?.trim() || null,
      message: message?.trim() || null,
    }

    // Save to database
    const submission = await prisma.contactSubmission.create({
      data: submissionData,
    })

    // Send notifications (don't wait for them, run in background)
    Promise.all([
      sendEmailNotification(submissionData),
      sendTelegramNotification(submissionData),
    ]).then(([emailResult, telegramResult]) => {
      console.log('Email notification:', emailResult.success ? 'sent' : 'failed')
      console.log('Telegram notification:', telegramResult.success ? 'sent' : 'failed')
    }).catch((error) => {
      console.error('Error sending notifications:', error)
    })

    return NextResponse.json(
      { success: true, message: 'Заявка успешно отправлена!' },
      { status: 200 }
    )
  } catch (error) {
    console.error('Error saving contact submission:', error)
    return NextResponse.json(
      { error: 'Произошла ошибка при отправке заявки' },
      { status: 500 }
    )
  }
}
