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

// Email validation schema
const subscribeSchema = z.object({
  email: z.string().email("Please enter a valid email address"),
  utmSource: z.string().optional(),
  utmCampaign: z.string().optional(),
  website: z.string().optional(), // Honeypot field
})

export const runtime = "edge" // Edge runtime for better compatibility

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

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

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

    const { email, utmSource, utmCampaign, website } = result.data

    // Check honeypot field - if it's filled, it's likely a bot
    if (website && website.length > 0) {
      // Return success to the bot but don't process
      return NextResponse.json({ success: true }, { status: 200 })
    }

    // Log the signup to Vercel logs
    console.log(`New signup: ${email} (source: ${utmSource || "direct"})`)

    // Create a data object for the new signup
    const signupData = {
      email,
      utmSource: utmSource || "direct",
      utmCampaign: utmCampaign || "website",
      timestamp: new Date().toISOString(),
    }

    // Store the email in memory (we'll use Buttondown as the primary storage)
    let emailAlreadyExists = false

    // Try to use Buttondown if configured
    const buttondownApiKey = process.env.BD_API_TOKEN
    if (buttondownApiKey) {
      try {
        // Format the request body according to Buttondown API requirements
        // The key change here is using "email_address" instead of "email"
        const buttondownPayload = {
          email_address: email, // Changed from "email" to "email_address"
          tags: ["waitlist"],
          metadata: {
            utm_source: utmSource || "direct",
            utm_campaign: utmCampaign || "website",
            signup_date: new Date().toISOString(),
          },
          referrer_url: process.env.NEXT_PUBLIC_SITE_URL || "https://quantumverify.io",
          notes: "Signed up via landing page waitlist form",
        }

        const response = await fetch("https://api.buttondown.email/v1/subscribers", {
          method: "POST",
          headers: {
            Authorization: `Token ${buttondownApiKey}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify(buttondownPayload),
        })

        const responseData = await response.json()

        if (!response.ok) {
          console.error("Buttondown API error:", responseData)

          // Check if the email already exists
          if (response.status === 400 && responseData.email_address?.[0]?.includes("already exists")) {
            emailAlreadyExists = true
          }
        } else {
          console.log("Successfully added to Buttondown:", email)
        }
      } catch (error) {
        console.error("Buttondown API error:", error)
        // Continue even if Buttondown fails
      }
    }

    // If email already exists in Buttondown, return conflict status
    if (emailAlreadyExists) {
      return NextResponse.json({ error: "You're already on our waitlist!" }, { status: 409 })
    }

    // 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 signup information
        const emailBody = `
          <h2>New waitlist signup received</h2>
          <p><strong>Email:</strong> ${email}</p>
          <p><strong>Source:</strong> ${utmSource || "direct"}</p>
          <p><strong>Campaign:</strong> ${utmCampaign || "none"}</p>
          <p><strong>Date:</strong> ${new Date().toISOString()}</p>
        `

        // Send notification email
        const notificationResponse = 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: "waitlist@quantumverify.io",
            to: "lukasz.dziewiecki@quantumverify.io",
            subject: "New Waitlist Signup",
            html: emailBody,
          }),
        })

        if (!notificationResponse.ok) {
          console.error("Failed to send notification email:", await notificationResponse.text())
        }

        // Add to Resend audience/list
        try {
          const audienceResponse = await fetch("https://api.resend.com/audiences/1234/contacts", {
            // Replace 1234 with your actual audience ID
            method: "POST",
            headers: {
              Authorization: `Bearer ${process.env.RESEND_API_KEY}`,
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              email: email,
              first_name: "",
              last_name: "",
              data: {
                utm_source: utmSource || "direct",
                utm_campaign: utmCampaign || "website",
                signup_date: new Date().toISOString(),
              },
            }),
          })

          if (!audienceResponse.ok) {
            console.error("Failed to add to Resend audience:", await audienceResponse.text())
          } else {
            console.log("Successfully added to Resend audience:", email)
          }
        } catch (audienceError) {
          console.error("Failed to add to Resend audience:", audienceError)
        }
      } catch (emailError) {
        console.error("Failed to send notification email:", emailError)
        // Continue with success response even if notification email fails
      }
    }

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