import { type NextRequest, NextResponse } from "next/server"
import { z } from "zod"

// Contact form validation schema
const contactSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters"),
  email: z.string().email("Please enter a valid email address"),
  company: z.string().optional(),
  message: z.string().min(10, "Message must be at least 10 characters"),
})

export const runtime = "edge"

export async function POST(request: NextRequest) {
  try {
    // Parse the request body
    const body = await request.json()

    // Validate the request body
    const result = contactSchema.safeParse(body)

    if (!result.success) {
      return NextResponse.json({ error: "Invalid request data", details: result.error.format() }, { status: 400 })
    }

    const { name, email, company, message } = result.data

    // Log the contact request to Vercel logs
    console.log(`New contact request from: ${name} (${email})`)

    // Send notification email to founder if RESEND_API_KEY is configured
    if (process.env.RESEND_API_KEY) {
      try {
        // Create a simple email body with the contact information
        const emailBody = `
          <h2>New contact request received</h2>
          <p><strong>Name:</strong> ${name}</p>
          <p><strong>Email:</strong> ${email}</p>
          <p><strong>Company:</strong> ${company || "Not provided"}</p>
          <p><strong>Message:</strong> ${message}</p>
          <p><strong>Date:</strong> ${new Date().toISOString()}</p>
        `

        const response = await fetch("https://api.resend.com/emails", {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.RESEND_API_KEY}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            from: "contact@quantumverify.io",
            to: "lukasz.dziewiecki@quantumverify.io",
            subject: `New Contact Request: ${name}`,
            html: emailBody,
            reply_to: email,
          }),
        })

        if (!response.ok) {
          const errorData = await response.json()
          console.error("Resend API error:", errorData)
          return NextResponse.json({ error: "Failed to send email" }, { status: 500 })
        }
      } catch (emailError) {
        console.error("Failed to send notification email:", emailError)
        return NextResponse.json({ error: "Failed to send email" }, { status: 500 })
      }
    } else {
      console.warn("RESEND_API_KEY not configured, skipping email notification")
    }

    // Return success
    return NextResponse.json({ success: true }, { status: 201 })
  } catch (error) {
    console.error("Contact form error:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}
