import { extname, join, resolve } from 'path';
import * as fs from 'fs';
import { v4 as uuidv4 } from 'uuid';
import { logWarn } from '../../../telemetry/telemetry';

export const resolveShootingDir = (shootingId: string): string =>
  resolve(process.env.UPLOAD_PATH || __dirname, `shootings/${shootingId}`);

export const editFileName = (
  req: any,
  file: Express.Multer.File,
  callback: (error: Error | null, filename: string) => void,
) => {
  const originalNameWithoutExt = file.originalname.split('.').shift() || '';
  const originalExt = extname(file.originalname).toLowerCase();
  let newFilename = `${originalNameWithoutExt}-${new Date().getTime()}${originalExt}`;

  // Deux fichiers de même nom d'origine traités dans la même milliseconde
  // produisent le même nom cible : le second écrase/corrompt le premier et la
  // galerie affiche la même image en double. On détecte, on trace, on dévie.
  const shootingId: string | undefined = req?.query?.shooting_id;
  if (shootingId) {
    const destination = join(resolveShootingDir(shootingId), newFilename);
    if (fs.existsSync(destination)) {
      const safeFilename = `${originalNameWithoutExt}-${new Date().getTime()}-${uuidv4().slice(0, 8)}${originalExt}`;
      logWarn(
        'Upload : collision de nom de fichier détectée — un fichier du même nom existe déjà pour ce shooting. ' +
          "Sans déviation, l'image existante aurait été écrasée (image altérée) et affichée en double.",
        {
          'shooting.id': shootingId,
          'file.originalname': file.originalname,
          'file.colliding_name': newFilename,
          'file.renamed_to': safeFilename,
        },
      );
      newFilename = safeFilename;
    }
  }

  callback(null, newFilename);
};

export const imageFileFilter = (
  _req: any,
  file: Express.Multer.File,
  callback: (error: Error | null, acceptFile: boolean) => void,
) => {
  if (
    !file.originalname.match(/\.(jpg|jpeg|png|gif|webp|heic|heif|raw|tiff)$/i)
  ) {
    return callback(
      new Error(
        'Format de fichier non supporté. Les formats acceptés sont : JPG, JPEG, PNG, GIF, WEBP, HEIC, HEIF, RAW, TIFF',
      ),
      false,
    );
  }
  callback(null, true);
};
