// utils/decryptMediaContent.js   (ES modules)
import fs   from 'fs';
import path from 'path';
import axios from 'axios';
import mime  from 'mime-types';
import { decryptMedia } from '@open-wa/wa-automate';
import { log } from '../logger.js';

// 🔒 quita caracteres que rompen rutas
const safe = s => (s || '').replace(/[\\/:*?"<>|]/g, '_');

export async function decryptMediaContent(
  mediaInfo,
  outputDir = 'media/dec',
  rawDir   = 'media/raw',
  filename = null
) {
  const { clientUrl, t, filehash, msgId, type } = mediaInfo;
  let   { mimetype } = mediaInfo;

  if (!clientUrl) {
    log('error', '❌  Sin clientUrl, no se puede bajar');
    return null;
  }

  // deducir mimetype si falta
  if (!mimetype) {
    mimetype =
      mime.lookup(clientUrl) ||
      (type?.startsWith('image') && 'image/jpeg') ||
      (type?.startsWith('video') && 'video/mp4') ||
      'application/octet-stream';
  }

  const ext      = mime.extension(mimetype) || 'bin';
  const baseName = safe(filename || msgId || filehash?.slice(0,16) || `file_${t||Date.now()}`);
  const rawPath  = path.join(rawDir , `${baseName}.enc`);
  const decPath  = path.join(outputDir, `${baseName}.${ext}`);

  if (fs.existsSync(decPath)) return decPath;

  fs.mkdirSync(rawDir   , { recursive: true });
  fs.mkdirSync(outputDir, { recursive: true });

  try {
    /* ───── descarga RAW (solo si no existe) ───── */
    if (!fs.existsSync(rawPath)) {
      const { data } = await axios
        .get(clientUrl, { responseType: 'arraybuffer' })
        .catch(e => {
          if (e.response?.status === 410) throw new Error('URL expirada (410)');
          throw e;
        });
      fs.writeFileSync(rawPath, Buffer.from(data));
    }

    /* ───── inyectar RAW para que decryptMedia no lo vuelva a bajar ───── */
    const fake = {
      ...mediaInfo,
      mimetype,
      mimeType: mimetype,
      _data: {
        ...mediaInfo,
        mimetype,
        mimeType: mimetype,
        _raw: fs.readFileSync(rawPath)
      }
    };

    const plain = await decryptMedia(fake);
    if (!plain?.length) throw new Error('descifrado vacío');

    fs.writeFileSync(decPath, plain);
    log('info', `✔️  ${type || ext} → ${decPath}`);
    return decPath;
  } catch (e) {
    log('error', `❌  decryptMedia falló → ${e.message}`);
    return null;
  }
}
