import { query } from '../db/connection.js';
import sharp from 'sharp';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DATA_DIR = path.resolve(__dirname, '../../data/images');

async function ensureDir(dir: string) {
  await fs.promises.mkdir(dir, { recursive: true });
}

export async function saveRecipeImage(recipeId: string, buffer: Buffer) {
  const { rows } = await query('SELECT id FROM recipes WHERE id = $1', [recipeId]);
  if (rows.length === 0) return null;

  const dir = path.join(DATA_DIR, 'recipes', recipeId);
  await ensureDir(dir);

  await sharp(buffer).resize({ width: 1200, withoutEnlargement: true }).webp({ quality: 80 }).toFile(path.join(dir, 'hero.webp'));
  await sharp(buffer).resize({ width: 400, withoutEnlargement: true }).webp({ quality: 70 }).toFile(path.join(dir, 'hero_thumb.webp'));

  const imagePath = `/images/recipes/${recipeId}/hero.webp`;
  await query('UPDATE recipes SET image_url = $1, updated_at = NOW() WHERE id = $2', [imagePath, recipeId]);
  return { image_url: imagePath, thumb_url: `/images/recipes/${recipeId}/hero_thumb.webp` };
}

export async function saveStepImage(recipeId: string, stepNumber: number, buffer: Buffer) {
  const { rows } = await query('SELECT id FROM steps WHERE recipe_id = $1 AND step_number = $2', [recipeId, stepNumber]);
  if (rows.length === 0) return null;
  const step = rows[0];

  const dir = path.join(DATA_DIR, 'recipes', recipeId, 'steps');
  await ensureDir(dir);

  const filename = `step_${stepNumber}.webp`;
  await sharp(buffer).resize({ width: 1200, withoutEnlargement: true }).webp({ quality: 80 }).toFile(path.join(dir, filename));

  const imageUrl = `/images/recipes/${recipeId}/steps/${filename}`;
  await query('UPDATE steps SET image_url = $1 WHERE id = $2', [imageUrl, step.id]);
  return { image_url: imageUrl };
}

export async function downloadAndSaveImage(recipeId: string, url: string) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
  const buffer = Buffer.from(await response.arrayBuffer());
  return saveRecipeImage(recipeId, buffer);
}
