import sharp from "sharp";
import path from "path";
import fs from "fs";

const uploadDir = path.join(process.cwd(), "client/public/uploads");

export async function optimizeImage(filePath: string): Promise<{ webp: string; thumb: string }> {
  const ext = path.extname(filePath);
  const baseName = path.basename(filePath, ext);
  const webpPath = path.join(uploadDir, `${baseName}.webp`);
  const thumbPath = path.join(uploadDir, `${baseName}-thumb.webp`);

  const image = sharp(filePath);
  const metadata = await image.metadata();
  const width = metadata.width || 1200;

  await sharp(filePath)
    .resize({ width: Math.min(width, 1200), withoutEnlargement: true })
    .webp({ quality: 80 })
    .toFile(webpPath);

  await sharp(filePath)
    .resize({ width: 400, withoutEnlargement: true })
    .webp({ quality: 65 })
    .toFile(thumbPath);

  if (filePath !== webpPath && ext.toLowerCase() !== ".webp") {
    fs.unlinkSync(filePath);
  }

  console.log(`[image-optimizer] Optimized: ${baseName}.webp (full + thumb)`);

  return {
    webp: `/uploads/${baseName}.webp`,
    thumb: `/uploads/${baseName}-thumb.webp`,
  };
}
