const fs = require('fs');
const path = require('path');
const axios = require('axios');
const logger = require('./logger');

const CACHE_DIR = path.resolve(process.cwd(), 'cache');

const ensureCacheDir = () => {
  if (!fs.existsSync(CACHE_DIR)) {
    fs.mkdirSync(CACHE_DIR, { recursive: true });
  }
};

const extractExtension = (url) => {
  try {
    const parsed = new URL(url);
    const ext = path.extname(parsed.pathname);
    if (ext) return ext.split('?')[0];
  } catch (error) {
    // ignore
  }
  return '.jpg';
};

const buildFileName = ({ isbn, locale, ext }) => {
  const safeLocale = locale || 'global';
  return `${isbn}_${safeLocale}_thumbnail${ext}`;
};

const downloadImage = async (url, destination) => {
  const response = await axios.get(url, { responseType: 'arraybuffer' });
  fs.writeFileSync(destination, response.data);
  logger.success(`🖼️ Thumbnail indirildi -> ${destination}`);
};

const cacheThumbnail = async ({ isbn, locale, url }) => {
  if (!url || !isbn) {
    return null;
  }

  ensureCacheDir();

  const ext = extractExtension(url);
  const fileName = buildFileName({ isbn, locale, ext });
  const filePath = path.join(CACHE_DIR, fileName);
  const relativePath = path.relative(process.cwd(), filePath);

  if (fs.existsSync(filePath)) {
    logger.info(`🗂️ Thumbnail cache'de bulundu: ${relativePath}`);
    return relativePath;
  }

  try {
    await downloadImage(url, filePath);
    return relativePath;
  } catch (error) {
    logger.warn(`Thumbnail indirilemedi: ${error.message}`);
    return null;
  }
};

module.exports = {
  cacheThumbnail,
  CACHE_DIR
};
