import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { ContactSchema } from '@/lib/validations'

export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const parsed = ContactSchema.safeParse(body)
    if (!parsed.success) {
      return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
    }

    const message = await prisma.contactMessage.create({
      data: parsed.data,
    })

    return NextResponse.json({ data: message }, { status: 201 })
  } catch (error) {
    console.error('Contact form error:', error)
    return NextResponse.json({ error: 'Server error' }, { status: 500 })
  }
}

export async function GET() {
  try {
    const messages = await prisma.contactMessage.findMany({
      where: { deletedAt: null },
      orderBy: { createdAt: 'desc' },
    })
    return NextResponse.json({ data: messages })
  } catch {
    return NextResponse.json({ error: 'Server error' }, { status: 500 })
  }
}
