import { Controller, Get } from '@nestjs/common';
import { ShootingRepo } from '../../repos/shooting.repo';
import { CustomerRepo } from '../../repos/customer.repo';
import { generateManifest } from '../../functions/generate-manifest';
import { generateManifestCustomer } from '../../functions/generate-manifest-customer';

@Controller('shootings')
export class RegenerateAllManifests {
  constructor(
    private shootingRepo: ShootingRepo,
    private customerRepo: CustomerRepo,
  ) {}

  @Get('regenerate-all-manifests')
  async execute() {
    console.log('Début de la régénération de tous les manifests...');

    try {
      const shootings = await this.shootingRepo.findAll();
      console.log(`${shootings.length} shootings trouvés`);

      const customers = await this.customerRepo.findAll();
      console.log(`${customers.length} clients trouvés`);

      let shootingManifestsCount = 0;
      let customerManifestsCount = 0;
      let errors = 0;

      for (const shooting of shootings) {
        try {
          console.log(
            `Régénération du manifest pour le shooting ${shooting.id}...`,
          );
          
          // Vérifier que les photos sont bien incluses
          if (!shooting.photos || shooting.photos.length === 0) {
            console.log(`Attention: Le shooting ${shooting.id} n'a pas de photos ou les photos ne sont pas chargées`);
            console.log(`Récupération du shooting complet avec photos pour ${shooting.id}`);
            const completeShootingData = await this.shootingRepo.findById(shooting.id);
            
            if (completeShootingData && completeShootingData.photos && completeShootingData.photos.length > 0) {
              console.log(`Shooting ${shooting.id} récupéré avec ${completeShootingData.photos.length} photos`);
              await generateManifest(completeShootingData);
            } else {
              console.log(`Le shooting ${shooting.id} n'a pas de photos, génération du manifest sans photos`);
              await generateManifest(shooting);
            }
          } else {
            console.log(`Le shooting ${shooting.id} a ${shooting.photos.length} photos`);
            await generateManifest(shooting);
          }
          
          shootingManifestsCount++;
        } catch (error) {
          console.error(
            `Erreur lors de la régénération du manifest pour le shooting ${shooting.id}:`,
            error,
          );
          errors++;
        }
      }

      for (const customer of customers) {
        try {
          console.log(
            `Régénération du manifest pour le client ${customer.id}...`,
          );
          await generateManifestCustomer(customer);
          customerManifestsCount++;
        } catch (error) {
          console.error(
            `Erreur lors de la régénération du manifest pour le client ${customer.id}:`,
            error,
          );
          errors++;
        }
      }

      console.log('Régénération de tous les manifests terminée');

      return {
        success: true,
        stats: {
          totalShootings: shootings.length,
          totalCustomers: customers.length,
          shootingManifestsRegenerated: shootingManifestsCount,
          customerManifestsRegenerated: customerManifestsCount,
          errors,
        },
        message: `Régénération terminée : ${shootingManifestsCount} manifests de shooting et ${customerManifestsCount} manifests de client ont été régénérés avec ${errors} erreurs.`,
      };
    } catch (error) {
      console.error('Erreur lors de la régénération des manifests:', error);
      return {
        success: false,
        error: error.message,
        message:
          'Une erreur est survenue lors de la régénération des manifests.',
      };
    }
  }
}
