import { NextRequest, NextResponse } from "next/server"
import { markEmailOpened } from "@/lib/db"
import fs from "fs"
import path from "path"

// Serve the byg-garanti image and track email opens
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params
  const quoteId = parseInt(id, 10)

  // Mark email as opened (only first time)
  if (!isNaN(quoteId)) {
    markEmailOpened(quoteId)
  }

  // Serve the image
  const imagePath = path.join(process.cwd(), "public", "byg_trans.png")

  try {
    const imageBuffer = fs.readFileSync(imagePath)

    return new NextResponse(imageBuffer, {
      headers: {
        "Content-Type": "image/png",
        "Cache-Control": "no-cache, no-store, must-revalidate",
        Pragma: "no-cache",
        Expires: "0",
      },
    })
  } catch {
    // Return a 1x1 transparent pixel if image not found
    const pixel = Buffer.from(
      "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
      "base64"
    )
    return new NextResponse(pixel, {
      headers: {
        "Content-Type": "image/png",
        "Cache-Control": "no-cache",
      },
    })
  }
}
