import { q as query } from '../../../chunks/db_Du3AmLCY.mjs';
import sharp from 'sharp';
import fs from 'node:fs';
import path from 'node:path';
export { renderers } from '../../../renderers.mjs';

const cache = /* @__PURE__ */ new Map();
const CACHE_TTL = 36e5;
const GET = async ({ params }) => {
  const id = Number(params.id);
  if (!id || isNaN(id)) {
    return new Response("Bad request", { status: 400 });
  }
  const cached = cache.get(id);
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return new Response(cached.buffer, {
      headers: {
        "Content-Type": "image/webp",
        "Cache-Control": "public, max-age=86400"
      }
    });
  }
  const result = await query(
    "SELECT cutout_image_url, image_url FROM products WHERE id = $1",
    [id]
  );
  if (result.rows.length === 0) {
    return new Response("Not found", { status: 404 });
  }
  const row = result.rows[0];
  const cutoutUrl = row.cutout_image_url;
  const fallbackUrl = row.image_url;
  if (!cutoutUrl && !fallbackUrl) {
    return new Response("No image", { status: 404 });
  }
  try {
    let inputBuffer = null;
    if (cutoutUrl && (cutoutUrl.startsWith("/cutouts/") || cutoutUrl.startsWith("./cutouts/"))) {
      const localPath = path.resolve(
        process.cwd(),
        "public",
        cutoutUrl.startsWith("/") ? cutoutUrl.slice(1) : cutoutUrl
      );
      if (fs.existsSync(localPath)) {
        inputBuffer = fs.readFileSync(localPath);
      }
    }
    if (!inputBuffer && fallbackUrl && fallbackUrl.startsWith("http")) {
      const response = await fetch(fallbackUrl, {
        signal: AbortSignal.timeout(8e3)
      });
      if (response.ok) {
        inputBuffer = Buffer.from(await response.arrayBuffer());
      }
    }
    if (!inputBuffer) {
      return new Response("Image unavailable", { status: 404 });
    }
    const webpBuffer = await sharp(inputBuffer).resize(600, 600, { fit: "contain", background: { r: 0, g: 0, b: 0, alpha: 0 } }).webp({ quality: 80 }).toBuffer();
    cache.set(id, { buffer: webpBuffer, timestamp: Date.now() });
    if (cache.size > 500) {
      const now = Date.now();
      for (const [key, val] of cache) {
        if (now - val.timestamp > CACHE_TTL) cache.delete(key);
      }
    }
    return new Response(webpBuffer, {
      headers: {
        "Content-Type": "image/webp",
        "Cache-Control": "public, max-age=86400"
      }
    });
  } catch (err) {
    console.error(`Image proxy error for product ${id}:`, err);
    if (fallbackUrl?.startsWith("http")) {
      return Response.redirect(fallbackUrl, 302);
    }
    return new Response("Error processing image", { status: 500 });
  }
};

const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  GET
}, Symbol.toStringTag, { value: 'Module' }));

const page = () => _page;

export { page };
