import type { APIRoute } from 'astro';
import { query } from '../../../lib/db';
import sharp from 'sharp';
import fs from 'node:fs';
import path from 'node:path';

// Simple in-memory cache for converted images
const cache = new Map<number, { buffer: Buffer; timestamp: number }>();
const CACHE_TTL = 3600_000; // 1 hour in-memory

export const GET: APIRoute = async ({ params }) => {
  const id = Number(params.id);
  if (!id || isNaN(id)) {
    return new Response('Bad request', { status: 400 });
  }

  // Check in-memory cache
  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',
      },
    });
  }

  // Look up image URL from DB
  const result = await query<any>(
    '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: string | null = row.cutout_image_url;
  const fallbackUrl: string | null = row.image_url;

  if (!cutoutUrl && !fallbackUrl) {
    return new Response('No image', { status: 404 });
  }

  try {
    let inputBuffer: Buffer | null = null;

    // Try cutout first (local file)
    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);
      }
    }

    // Fallback to external image_url if cutout not on disk
    if (!inputBuffer && fallbackUrl && fallbackUrl.startsWith('http')) {
      const response = await fetch(fallbackUrl, {
        signal: AbortSignal.timeout(8000),
      });
      if (response.ok) {
        inputBuffer = Buffer.from(await response.arrayBuffer());
      }
    }

    if (!inputBuffer) {
      return new Response('Image unavailable', { status: 404 });
    }

    // Convert to WebP
    const webpBuffer = await sharp(inputBuffer)
      .resize(600, 600, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
      .webp({ quality: 80 })
      .toBuffer();

    // Store in cache
    cache.set(id, { buffer: webpBuffer, timestamp: Date.now() });

    // Evict old entries if cache gets too large
    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);
    // Fallback: redirect to original URL
    if (fallbackUrl?.startsWith('http')) {
      return Response.redirect(fallbackUrl, 302);
    }
    return new Response('Error processing image', { status: 500 });
  }
};
