import {
  BadRequestException,
  Controller,
  Post,
  Query,
  Req,
  UploadedFiles,
  UseInterceptors,
} from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { FastifyFilesInterceptor } from '../../interceptors/fastify-files-interceptor';
import { diskStorage } from 'fastify-multer';
import {
  editFileName,
  imageFileFilter,
  resolveShootingDir,
} from '../../functions/upload.functions';
import { filesMapper } from '../../mappers/file.mapper';
import { FastifyRequest } from 'fastify';
import * as fs from 'fs';
import { Photo } from '../../domain/Photo';
import { PhotoRepo } from '../../repos/photo.repo';
import { ShootingRepo } from '../../repos/shooting.repo';
import {
  logError,
  logInfo,
  logWarn,
  withSpan,
} from '../../../../telemetry/telemetry';

@Controller('shootings')
export class UploadPhotos {
  constructor(
    private photoRepo: PhotoRepo,
    private shootingRepo: ShootingRepo,
    private eventEmitter: EventEmitter2,
  ) {}

  @Post('multiple-file')
  @UseInterceptors(
    FastifyFilesInterceptor('photo_url', 500, {
      storage: diskStorage({
        destination: async (req, file, cb) => {
          const query: { shooting_id: string } = req.query as any;

          if (!query.shooting_id) {
            return cb(
              new BadRequestException("L'identifiant du shooting est manquant"),
              null,
            );
          }

          const uploadPath = resolveShootingDir(query.shooting_id);

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

          cb(null, uploadPath);
        },
        filename: editFileName,
      }) as any,
      fileFilter: imageFileFilter,
    }),
  )
  async multiple(
    @Req() req: FastifyRequest,
    @UploadedFiles() files: Express.Multer.File[],
    @Query() query: { shooting_id: string },
  ) {
    if (!files || files.length === 0) {
      throw new Error('No files uploaded');
    }

    return withSpan(
      'UploadPhotos.multiple',
      {
        'shooting.id': query.shooting_id,
        'upload.file_count': files.length,
      },
      async () => {
        await this.auditBatchIntegrity(files, query.shooting_id);

        const photosToCreate = files.map((file, index) => {
          const photo = Photo.create({
            filename: file.filename,
            originalname: file.originalname,
            path: file.path,
            shootingId: query.shooting_id,
            createdAt: new Date(),
            updatedAt: new Date(),
            order: index + 1,
          });

          return photo;
        });

        await this.photoRepo.createMany(photosToCreate);

        const shooting = await this.shootingRepo.findById(query.shooting_id);

        if (shooting) {
          logInfo(
            `Upload terminé : ${files.length} photo(s) ajoutée(s) au shooting ${shooting.id}`,
            {
              'shooting.id': shooting.id,
              'upload.file_count': files.length,
            },
          );
          this.eventEmitter.emit('shooting.updated', shooting);
        }

        return {
          ...query,
          photo_url: filesMapper({ files, req }),
        };
      },
    );
  }

  /**
   * Contrôles d'intégrité du lot uploadé, pour capter les images altérées
   * ou dupliquées observées en production sans pouvoir les reproduire :
   * fichiers absents/tronqués sur disque, chemins en double dans le lot,
   * ré-upload d'un fichier déjà présent dans le shooting (retry/double submit).
   */
  private async auditBatchIntegrity(
    files: Express.Multer.File[],
    shootingId: string,
  ): Promise<void> {
    for (const file of files) {
      try {
        const stat = await fs.promises.stat(file.path);
        if (stat.size === 0 || (file.size != null && stat.size !== file.size)) {
          logError(
            'Upload : fichier tronqué ou altéré sur disque — la taille écrite ne correspond pas à la taille reçue',
            {
              'shooting.id': shootingId,
              'file.originalname': file.originalname,
              'file.filename': file.filename,
              'file.expected_size': file.size ?? -1,
              'file.disk_size': stat.size,
            },
          );
        }
      } catch {
        logError(
          "Upload : fichier annoncé par multer mais introuvable sur disque à la fin de l'upload",
          {
            'shooting.id': shootingId,
            'file.originalname': file.originalname,
            'file.filename': file.filename,
            'file.path': file.path,
          },
        );
      }
    }

    const pathCounts = new Map<string, number>();
    for (const file of files) {
      pathCounts.set(file.path, (pathCounts.get(file.path) ?? 0) + 1);
    }
    for (const [path, count] of pathCounts) {
      if (count > 1) {
        logError(
          'Upload : plusieurs fichiers du lot ont été écrits au MÊME chemin — les écritures se sont écrasées entre elles (image altérée + doublon garanti en galerie)',
          {
            'shooting.id': shootingId,
            'file.path': path,
            'file.count': count,
          },
        );
      }
    }

    const originalNames = new Set(files.map((file) => file.originalname));
    if (originalNames.size < files.length) {
      logWarn(
        "Upload : le lot contient plusieurs fichiers portant le même nom d'origine",
        {
          'shooting.id': shootingId,
          'upload.file_count': files.length,
          'upload.distinct_names': originalNames.size,
        },
      );
    }

    const existingPhotos = await this.photoRepo.findByShootingId(shootingId);
    const existingNames = new Set(
      existingPhotos.map((photo) => photo.originalname),
    );
    const reUploaded = files.filter((file) =>
      existingNames.has(file.originalname),
    );
    if (reUploaded.length > 0) {
      logWarn(
        'Upload : doublon potentiel — des fichiers de même nom existent déjà dans ce shooting (retry réseau ou double soumission probable)',
        {
          'shooting.id': shootingId,
          'upload.duplicate_count': reUploaded.length,
          'upload.duplicate_names': reUploaded
            .slice(0, 20)
            .map((file) => file.originalname)
            .join(', '),
        },
      );
    }
  }
}
