import { tasksService } from '../src/services/task-management/tasks';
import { TaskStatus, TaskPriority } from '../src/lib/types';
import { prisma } from '../src/services/core/database';

/**
 * Script pour ajouter des données de test avec tags et variété
 */
async function seedTestData() {
  console.log('🌱 Ajout de données de test...');
  console.log('================================');

  // Récupérer le premier user ou créer un user temporaire
  let userId: string;
  const firstUser = await prisma.user.findFirst({
    orderBy: { createdAt: 'asc' },
  });

  if (firstUser) {
    userId = firstUser.id;
    console.log(`👤 Utilisation du user existant: ${firstUser.email}`);
  } else {
    // Créer un user temporaire pour les tests
    const tempUser = await prisma.user.create({
      data: {
        email: 'test@example.com',
        name: 'Test User',
        password: '$2b$10$temp', // Mot de passe temporaire
      },
    });
    userId = tempUser.id;
    console.log(`👤 User temporaire créé: ${tempUser.email}`);
  }

  const testTasks = [
    {
      title: '🎨 Design System Implementation',
      description:
        'Create and implement a comprehensive design system with reusable components',
      status: 'in_progress' as TaskStatus,
      priority: 'high' as TaskPriority,
      tags: ['design', 'ui', 'frontend'],
      dueDate: new Date('2025-12-31'),
    },
    {
      title: '🔧 API Performance Optimization',
      description:
        'Optimize API endpoints response time and implement pagination',
      status: 'todo' as TaskStatus,
      priority: 'medium' as TaskPriority,
      tags: ['backend', 'performance', 'api'],
      dueDate: new Date('2025-12-15'),
    },
    {
      title: '✅ Test Coverage Improvement',
      description: 'Increase test coverage for core components and services',
      status: 'todo' as TaskStatus,
      priority: 'medium' as TaskPriority,
      tags: ['testing', 'quality'],
      dueDate: new Date('2025-12-20'),
    },
    {
      title: '📱 Mobile Responsive Design',
      description: 'Ensure all pages are fully responsive on mobile devices',
      status: 'todo' as TaskStatus,
      priority: 'high' as TaskPriority,
      tags: ['frontend', 'mobile', 'ui'],
      dueDate: new Date('2025-12-10'),
    },
    {
      title: '🔒 Security Audit',
      description: 'Conduct a comprehensive security audit of the application',
      status: 'backlog' as TaskStatus,
      priority: 'urgent' as TaskPriority,
      tags: ['security', 'audit'],
      dueDate: new Date('2026-01-15'),
    },
  ];

  let createdCount = 0;
  let errorCount = 0;

  for (const taskData of testTasks) {
    try {
      const task = await tasksService.createTask({
        ...taskData,
        ownerId: userId, // Ajouter l'ownerId
      });

      const statusEmoji = {
        backlog: '📋',
        todo: '⏳',
        in_progress: '🔄',
        freeze: '🧊',
        done: '✅',
        cancelled: '❌',
        archived: '📦',
      }[task.status];

      const priorityEmoji = {
        low: '🔵',
        medium: '🟡',
        high: '🔴',
        urgent: '🚨',
      }[task.priority];

      console.log(`  ${statusEmoji} ${priorityEmoji} ${task.title}`);
      console.log(`     Tags: ${task.tags?.join(', ') || 'aucun'}`);
      if (task.dueDate) {
        console.log(
          `     Échéance: ${task.dueDate.toLocaleDateString('fr-FR')}`
        );
      }
      console.log('');

      createdCount++;
    } catch (error) {
      console.error(
        `  ❌ Erreur pour "${taskData.title}":`,
        error instanceof Error ? error.message : error
      );
      errorCount++;
    }
  }

  console.log('📊 Résumé:');
  console.log(`   ✅ Tâches créées: ${createdCount}`);
  console.log(`   ❌ Erreurs: ${errorCount}`);

  // Afficher les stats finales
  const stats = await tasksService.getTaskStats(userId);
  console.log('');
  console.log('📈 Statistiques finales:');
  console.log(`   Total: ${stats.total} tâches`);
  console.log(`   À faire: ${stats.todo}`);
  console.log(`   En cours: ${stats.inProgress}`);
  console.log(`   Terminées: ${stats.completed}`);
  console.log(`   Annulées: ${stats.cancelled}`);
  console.log(`   Taux de completion: ${stats.completionRate}%`);
}

// Exécuter le script
if (require.main === module) {
  seedTestData()
    .then(() => {
      console.log('');
      console.log('✨ Données de test ajoutées avec succès !');
      process.exit(0);
    })
    .catch((error) => {
      console.error('💥 Erreur fatale:', error);
      process.exit(1);
    });
}

export { seedTestData };
