import { NextRequest, NextResponse } from 'next/server'
import { sendEmail } from '@/lib/email'
import { sendTelegramMessage } from '@/lib/telegram'

export async function POST(request: NextRequest) {
  try {
    const { phone, productName, productSlug } = await request.json()

    // Validate input
    if (!phone || !productName) {
      return NextResponse.json(
        { message: 'Необхідно вказати номер телефону та назву продукту' },
        { status: 400 }
      )
    }

    // Validate phone format
    const phoneRegex = /^(\+380|0)[0-9]{9}$/
    const cleanedPhone = phone.replace(/\s|-|\(|\)/g, '')
    if (!phoneRegex.test(cleanedPhone)) {
      return NextResponse.json(
        { message: 'Невірний формат номера телефону' },
        { status: 400 }
      )
    }

    const timestamp = new Date().toLocaleString('uk-UA', {
      timeZone: 'Europe/Kyiv',
      dateStyle: 'full',
      timeStyle: 'long',
    })

    // Send notifications (both email and telegram)
    const emailPromise = sendEmail({
      phone: cleanedPhone,
      productName,
      productSlug,
      timestamp,
    }).catch(error => {
      console.error('Email sending failed:', error.message)
      throw error // Re-throw to mark as failed
    })

    const telegramPromise = sendTelegramMessage({
      phone: cleanedPhone,
      productName,
      productSlug,
      timestamp,
    }).catch(error => {
      console.error('Telegram sending failed:', error.message)
      throw error // Re-throw to mark as failed
    })

    // Wait for both to complete
    const results = await Promise.allSettled([emailPromise, telegramPromise])

    const emailSuccess = results[0].status === 'fulfilled'
    const telegramSuccess = results[1].status === 'fulfilled'

    // Log results for debugging
    console.log(`Order notification results - Email: ${emailSuccess ? 'SUCCESS' : 'FAILED'}, Telegram: ${telegramSuccess ? 'SUCCESS' : 'FAILED'}`)

    // Success if at least one notification method worked
    if (emailSuccess || telegramSuccess) {
      let successMessage = 'Заявку успішно відправлено'

      if (emailSuccess && telegramSuccess) {
        successMessage += ' (Email та Telegram)'
      } else if (emailSuccess) {
        successMessage += ' (Email)'
      } else if (telegramSuccess) {
        successMessage += ' (Telegram)'
      }

      return NextResponse.json({
        message: successMessage,
        success: true,
        notifications: {
          email: emailSuccess,
          telegram: telegramSuccess
        }
      })
    }

    // Both failed - return error
    return NextResponse.json(
      { message: 'Помилка при відправці повідомлень. Спробуйте ще раз.' },
      { status: 500 }
    )
  } catch (error) {
    console.error('Error processing order:', error)
    return NextResponse.json(
      { message: 'Внутрішня помилка сервера' },
      { status: 500 }
    )
  }
}
