import { NextRequest, NextResponse } from "next/server"
import { createAdminClient } from "@/lib/supabase/admin"
import { PKPass } from "passkit-generator"
import fs from "fs"
import path from "path"

/**
 * Serve Apple Wallet .pkpass file
 * This endpoint generates and serves the actual .pkpass file
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const orderId = searchParams.get("orderId")
    const eventId = searchParams.get("eventId")

    if (!orderId || !eventId) {
      return NextResponse.json({ error: "Missing orderId or eventId" }, { status: 400 })
    }

    const supabase = createAdminClient()

    // Fetch order with tickets and event details
    const { data: order, error: orderError } = await supabase
      .from("orders")
      .select(
        "*, order_tickets(*), events(name, location, event_date, end_date, end_time, currency, start_time)"
      )
      .eq("id", orderId)
      .eq("event_id", eventId)
      .single()

    if (orderError || !order) {
      return NextResponse.json({ error: "Order not found" }, { status: 404 })
    }

    const event = order.events
    const tickets = order.order_tickets?.filter((t: any) => t.fulfillment_status === "pending") || []

    if (tickets.length === 0) {
      return NextResponse.json({ error: "No available tickets found" }, { status: 404 })
    }

    // Get Apple Wallet configuration
    const passTypeId = process.env.APPLE_WALLET_PASS_TYPE_ID
    const teamId = process.env.APPLE_WALLET_TEAM_ID
    const wwdrPath = process.env.APPLE_WALLET_WWDR_PATH

    if (!passTypeId || !teamId || !wwdrPath) {
      return NextResponse.json(
        {
          error: "Apple Wallet configuration incomplete",
          message: "Please configure APPLE_WALLET_* environment variables",
        },
        { status: 500 }
      )
    }

    // Resolve certificate paths - use separate PEM files
    // Handle both relative and absolute paths
    const resolvePath = (filePath: string): { resolved: string; tried: string[] } => {
      const tried: string[] = []
      
      // If absolute path, use as-is
      if (path.isAbsolute(filePath)) {
        tried.push(filePath)
        if (fs.existsSync(filePath)) {
          return { resolved: filePath, tried }
        }
        return { resolved: filePath, tried }
      }

      // Remove leading ./ if present
      const cleanPath = filePath.replace(/^\.\//, "")

      // Try different base paths
      const basePaths = [
        process.cwd(), // Current working directory (most common)
        path.join(process.cwd(), "frontend"), // If running from project root
      ]

      for (const base of basePaths) {
        const resolved = path.join(base, cleanPath)
        tried.push(resolved)
        if (fs.existsSync(resolved)) {
          return { resolved, tried }
        }
      }

      // Return the first tried path as fallback
      return { resolved: tried[0] || path.join(process.cwd(), cleanPath), tried }
    }

    const certsPathResult = resolvePath("certificates/apple-wallet")
    const wwdrPathResult = resolvePath(wwdrPath)
    const certsPath = certsPathResult.resolved
    const wwdrFullPath = wwdrPathResult.resolved
    const certPemPath = path.join(certsPath, "certificate.pem")
    const keyPemPath = path.join(certsPath, "key.pem")

    // Check if certificates exist with helpful error messages
    if (!fs.existsSync(wwdrFullPath)) {
      console.error("[WALLET] WWDR certificate not found:", {
        resolved: wwdrFullPath,
        env: wwdrPath,
        tried: wwdrPathResult.tried,
        cwd: process.cwd(),
      })
      return NextResponse.json(
        {
          error: "Apple WWDR certificate not found",
          resolvedPath: wwdrFullPath,
          envPath: wwdrPath,
          triedPaths: wwdrPathResult.tried,
          currentWorkingDirectory: process.cwd(),
          suggestion:
            "For production, use an absolute path in APPLE_WALLET_WWDR_PATH (e.g., /var/www/html/tikkets.com/new.tikkets.com/frontend/certificates/apple-wallet/wwdr.pem). Ensure the certificate file is deployed to your production server.",
        },
        { status: 500 }
      )
    }

    if (!fs.existsSync(certPemPath)) {
      console.error("[WALLET] Certificate not found:", certPemPath)
      return NextResponse.json(
        {
          error: "Apple Wallet certificate not found",
          path: certPemPath,
          certsPath: certsPath,
          note: "Expected certificate.pem in certificates/apple-wallet/",
          suggestion: "Ensure certificate.pem exists in the certificates/apple-wallet/ directory",
        },
        { status: 500 }
      )
    }

    if (!fs.existsSync(keyPemPath)) {
      console.error("[WALLET] Private key not found:", keyPemPath)
      return NextResponse.json(
        {
          error: "Apple Wallet private key not found",
          path: keyPemPath,
          certsPath: certsPath,
          note: "Expected key.pem in certificates/apple-wallet/",
          suggestion: "Ensure key.pem exists in the certificates/apple-wallet/ directory",
        },
        { status: 500 }
      )
    }

    // Generate pass for the first ticket
    const ticket = tickets[0]

    // Format event date
    const eventDate = event.event_date
      ? new Date(event.event_date).toISOString().split("T")[0]
      : new Date().toISOString().split("T")[0]

    // Generate unique pass ID
    const passId = `${order.customer_email}_${ticket.id}`.replace(/[^\w.-]/gi, "_")
    const serialNumber = `${passTypeId}.${passId}`

    // Read certificates
    const wwdrCert = fs.readFileSync(wwdrFullPath)
    const signerCert = fs.readFileSync(certPemPath)
    const signerKey = fs.readFileSync(keyPemPath)

    // Prepare file buffers (images)
    const fileBuffers: Record<string, Buffer> = {}
    const iconPath = path.join(certsPath, "icon.png")
    const logoPath = path.join(certsPath, "logo.png")
    const icon2xPath = path.join(certsPath, "icon@2x.png")
    const logo2xPath = path.join(certsPath, "logo@2x.png")

    if (fs.existsSync(iconPath)) {
      fileBuffers["icon.png"] = fs.readFileSync(iconPath)
    }
    if (fs.existsSync(logoPath)) {
      fileBuffers["logo.png"] = fs.readFileSync(logoPath)
    }
    if (fs.existsSync(icon2xPath)) {
      fileBuffers["icon@2x.png"] = fs.readFileSync(icon2xPath)
    }
    if (fs.existsSync(logo2xPath)) {
      fileBuffers["logo@2x.png"] = fs.readFileSync(logo2xPath)
    }

    // Create pass props
    // The library detects the type from having the eventTicket property
    const passProps: any = {
      serialNumber: serialNumber,
      description: "Event Ticket",
      organizationName: "Tikkets",
      logoText: "Tikkets",
      passTypeIdentifier: passTypeId,
      teamIdentifier: teamId,
      backgroundColor: "rgb(60, 65, 76)",
      foregroundColor: "rgb(255, 255, 255)",
      labelColor: "rgb(255, 255, 255)",
      // The eventTicket property tells the library this is an eventTicket type pass
      eventTicket: {},
    }

    // Create PKPass instance
    const pass = new PKPass(
      Object.keys(fileBuffers).length > 0 ? fileBuffers : {},
      {
        wwdr: wwdrCert,
        signerCert: signerCert,
        signerKey: signerKey,
        // Note: key.pem might have a passphrase, but we'll try without first
        // If it fails, you may need to add: signerKeyPassphrase: "your_key_passphrase"
      },
      passProps
    )

    // Explicitly set the pass type to eventTicket
    // This initializes the field arrays (primaryFields, secondaryFields, etc.)
    pass.type = "eventTicket"

    // Set the QR code barcode after type is set
    // This ensures the barcode is properly added to the pass
    const qrCodeValue = ticket.qr_code_data || "TICKET-ABC123"
    pass.setBarcodes({
      format: "PKBarcodeFormatQR",
      message: qrCodeValue,
      messageEncoding: "iso-8859-1",
    })

    // Now set the fields using the pass's field arrays
    pass.primaryFields.push({
      key: "event",
      label: "EVENT",
      value: event.name || "Event Ticket",
    })

    pass.secondaryFields.push({
      key: "venue",
      label: "VENUE",
      value: event.location || "Event Venue",
    })

    pass.secondaryFields.push({
      key: "date",
      label: "DATE",
      value: eventDate,
    })

    pass.auxiliaryFields.push({
      key: "ticket_type",
      label: "TICKET TYPE",
      value: ticket.ticket_name || "General Admission",
    })

    pass.auxiliaryFields.push({
      key: "ticket_number",
      label: "TICKET #",
      value: ticket.qr_code_data || "N/A",
    })

    pass.auxiliaryFields.push({
      key: "holder",
      label: "HOLDER",
      value: order.customer_name || "Guest User",
    })

    // Generate the .pkpass file
    const passBuffer = pass.getAsBuffer()

    // Return the .pkpass file
    return new NextResponse(passBuffer as any, {
      headers: {
        "Content-Type": "application/vnd.apple.pkpass",
        "Content-Disposition": `attachment; filename="ticket-${orderId}.pkpass"`,
        "Cache-Control": "no-cache, must-revalidate",
        Pragma: "no-cache",
      },
    })
  } catch (error: any) {
    console.error("[WALLET] Apple Wallet serve error:", error)
    return NextResponse.json(
      {
        error: error.message || "Failed to serve Apple Wallet pass",
        details: process.env.NODE_ENV === "development" ? error.stack : undefined,
      },
      { status: 500 }
    )
  }
}
