import { existsSync, mkdirSync } from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import sharp from 'sharp';

const uploadDirectory = path.join(process.cwd(), "public", "uploads");
const thumbnailDirectory = path.join(uploadDirectory, "thumbs");
const ensureUploadDirectories = () => {
  if (!existsSync(uploadDirectory)) {
    mkdirSync(uploadDirectory, { recursive: true });
  }
  if (!existsSync(thumbnailDirectory)) {
    mkdirSync(thumbnailDirectory, { recursive: true });
  }
};
const storeImageBuffer = async (sourceBuffer) => {
  ensureUploadDirectories();
  const id = randomUUID();
  const imageName = `${id}.webp`;
  const thumbnailName = `${id}-thumb.webp`;
  const imagePath = path.join(uploadDirectory, imageName);
  const thumbnailPath = path.join(thumbnailDirectory, thumbnailName);
  await sharp(sourceBuffer).rotate().resize({ width: 1400, withoutEnlargement: true }).webp({ quality: 82 }).toFile(imagePath);
  await sharp(sourceBuffer).rotate().resize(420, 260, { fit: "cover" }).webp({ quality: 76 }).toFile(thumbnailPath);
  return {
    image: `/uploads/${imageName}`,
    thumbnail: `/uploads/thumbs/${thumbnailName}`
  };
};
const downloadAndStoreImage = async (url) => {
  try {
    const response = await fetch(url, {
      headers: {
        "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
        accept: "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
        referer: "https://tass.ru/"
      }
    });
    if (!response.ok) {
      return null;
    }
    const contentType = response.headers.get("content-type") ?? "";
    if (!contentType.startsWith("image/")) {
      return null;
    }
    return storeImageBuffer(Buffer.from(await response.arrayBuffer()));
  } catch {
    return null;
  }
};

export { downloadAndStoreImage as d, storeImageBuffer as s };
