import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { resend, EMAIL_FROM } from '@/lib/resend'
import { buildOrderConfirmationEmail, buildAdminOrderNotificationEmail } from '@/lib/email-templates'

const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'info@varjoliitokauppa.fi'

type OrderItemInput = {
  id: string
  quantity: number
  price: number
  salePrice?: number
  selectedColor?: string | null
  selectedSize?: string | null
}

type OrderRequest = {
  customer: {
    name: string
    email: string
    phone: string
    address: string
    city: string
    zip: string
    notes?: string | null
  }
  items: OrderItemInput[]
  total: number | string
  shippingMethod: string
}

// POST /api/orders - Create a new order
export async function POST(request: Request) {
  const idempotencyKey = request.headers.get('Idempotency-Key')?.trim() || null
  try {
    if (idempotencyKey) {
      const existing = await prisma.order.findUnique({
        where: { idempotencyKey },
        include: {
          items: {
            include: { product: true },
          },
        },
      })
      if (existing) {
        return NextResponse.json(existing, { status: 200 })
      }
    }

    const body = (await request.json()) as OrderRequest
    const total =
      typeof body.total === 'string' ? parseFloat(body.total) : body.total
    const items = Array.isArray(body.items) ? body.items : []

    const order = await prisma.order.create({
      data: {
        idempotencyKey: idempotencyKey || null,
        customerName: body.customer.name,
        customerEmail: body.customer.email,
        customerPhone: body.customer.phone,
        customerAddress: body.customer.address,
        customerCity: body.customer.city,
        customerZip: body.customer.zip,
        shippingMethod: body.shippingMethod,
        notes: body.customer.notes || null,
        total,
        status: 'pending',
        items: {
          create: items.map((item) => ({
            productId: item.id,
            quantity: item.quantity,
            price: item.salePrice || item.price,
            selectedColor: item.selectedColor || null,
            selectedSize: item.selectedSize || null,
          })),
        },
      },
      include: {
        items: {
          include: {
            product: true,
          },
        },
      },
    })

    // Send emails (non-blocking – don't fail the order if emails fail)
    try {
      const customerEmail = buildOrderConfirmationEmail(order)
      const adminEmail = buildAdminOrderNotificationEmail(order)

      await Promise.allSettled([
        resend.emails.send({
          from: EMAIL_FROM,
          to: order.customerEmail,
          subject: customerEmail.subject,
          html: customerEmail.html,
        }),
        resend.emails.send({
          from: EMAIL_FROM,
          to: ADMIN_EMAIL,
          subject: adminEmail.subject,
          html: adminEmail.html,
        }),
      ])
    } catch (emailError) {
      console.error('Failed to send order emails:', emailError)
    }

    return NextResponse.json(order, { status: 201 })
  } catch (error) {
    console.error('Error creating order:', error)
    if (idempotencyKey) {
      const existing = await prisma.order.findUnique({
        where: { idempotencyKey },
        include: {
          items: {
            include: { product: true },
          },
        },
      })
      if (existing) {
        return NextResponse.json(existing, { status: 200 })
      }
    }
    return NextResponse.json({ error: 'Failed to create order' }, { status: 500 })
  }
}
