//docker cp backend/src/prisma/seed_support_bot.ts ai-learning-platform-backend:/app/src/prisma/seed_support_bot.ts
//docker-compose exec backend npx tsx src/prisma/seed_support_bot.ts

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
  log: ['warn', 'error'],
});

export async function seedSupportBot() {
  console.log('🌱 Starting support bot seed...');

  try {
    // Create support bot with the specified data
    const supportBotData = {
      name: 'Carla Test Bot',
      topic: 'English Onboarding',
      level: 'A1' as const,
      imageUrl: '',
      agentId: 'agent_1801k4z5jwb7ez48005e1ackkyta',
      description: 'Hi! Let\'s make a clear onboarding brief for you. We\'ll cover your role, tools, and first-week plan.',
      isActive: false,
    };

    console.log('🤖 Creating/updating support bot...');
    
    try {
      const existingBot = await prisma.bot.findFirst({
        where: { name: supportBotData.name },
      });

      if (existingBot) {
        // Check if the existing bot has a real agent ID (not a test one)
        const isTestAgentId = existingBot.agentId && existingBot.agentId.startsWith('test-agent-');
        const shouldPreserveAgentId = existingBot.agentId && !isTestAgentId;
        
        // Update existing bot, but preserve real agent IDs
        const updateData = {
          ...supportBotData,
          // Only update agentId if the existing one is a test agent ID or null
          agentId: shouldPreserveAgentId ? existingBot.agentId : supportBotData.agentId,
        };
        
        const bot = await prisma.bot.update({
          where: { id: existingBot.id },
          data: updateData,
        });
        
        if (shouldPreserveAgentId) {
          console.log('✅ Support bot updated:', bot.name, '(preserved existing agent ID:', existingBot.agentId, ')');
        } else {
          console.log('✅ Support bot updated:', bot.name, 'with agent ID:', bot.agentId);
        }
      } else {
        // Create new bot
        const bot = await prisma.bot.create({
          data: supportBotData,
        });
        console.log('✅ Support bot created:', bot.name, 'with agent ID:', bot.agentId);
      }

      console.log('🎉 Support bot seeding completed successfully!');
      console.log('📊 Bot Details:');
      console.log(`  - Name: ${supportBotData.name}`);
      console.log(`  - Topic: ${supportBotData.topic}`);
      console.log(`  - Level: ${supportBotData.level}`);
      console.log(`  - Agent ID: ${supportBotData.agentId}`);
      console.log(`  - Active: ${supportBotData.isActive}`);
      console.log('');
      console.log('⚠️  IMPORTANT: The bot is deactivated by default.');
      console.log('   To activate it, the connection with ElevenLabs will be automatically validated.');
      console.log('   If validation fails, the bot cannot be activated.');

    } catch (error) {
      console.error('❌ Error creating/updating support bot:', error);
      throw error;
    }

  } catch (error) {
    console.error('❌ Error during support bot seeding:', error);
    throw error;
  }
}

// Main function for CLI usage
async function main() {
  await seedSupportBot();
}

// Only run main if this file is executed directly
if (require.main === module) {
  // eslint-disable-next-line @typescript-eslint/prefer-top-level-await
  main()
    .catch((e) => {
      console.error('❌ Error during support bot seeding:', e);
      process.exit(1);
    })
    // eslint-disable-next-line @typescript-eslint/prefer-top-level-await
    .finally(async () => {
      await prisma.$disconnect();
    });
}
