require('dotenv').config();
const database = require('../config/database');
const { v4: uuidv4 } = require('uuid');

// Template data from your current project.types.js
const TEMPLATE_DATA = {
  'Business & Enterprise': [
    {
      type: 'healthcare',
      title: 'Healthcare Platform',
      description: 'Patient management, appointments, medical records, telehealth',
      icon: '🏥',
      gradient: 'from-blue-50 to-blue-100',
      border: 'border-blue-200',
      text: 'text-blue-900',
      subtext: 'text-blue-700',
      features: [
        {
          feature_id: 'user_auth',
          name: 'User Authentication',
          description: 'Secure login and registration for caregivers and admins',
          feature_type: 'essential',
          complexity: 'medium',
          display_order: 1
        },
        {
          feature_id: 'patient_management',
          name: 'Patient Management',
          description: 'Create, edit, and manage patient profiles with medical history',
          feature_type: 'essential',
          complexity: 'high',
          display_order: 2
        },
        {
          feature_id: 'appointment_scheduling',
          name: 'Appointment Scheduling',
          description: 'Schedule and manage patient appointments',
          feature_type: 'essential',
          complexity: 'medium',
          display_order: 3
        },
        {
          feature_id: 'call_scheduling',
          name: 'Automated Call Scheduling',
          description: 'Schedule automated calls to patients via Retell AI',
          feature_type: 'suggested',
          complexity: 'high',
          display_order: 4
        },
        {
          feature_id: 'admin_dashboard',
          name: 'Admin Dashboard',
          description: 'Analytics and usage tracking for administrators',
          feature_type: 'suggested',
          complexity: 'medium',
          display_order: 5
        }
      ]
    },
    {
      type: 'ecommerce',
      title: 'E-commerce Platform',
      description: 'Online store, payments, inventory, customer management',
      icon: '🛒',
      gradient: 'from-green-50 to-green-100',
      border: 'border-green-200',
      text: 'text-green-900',
      subtext: 'text-green-700',
      features: [
        {
          feature_id: 'user_auth',
          name: 'User Authentication',
          description: 'Customer registration and login system',
          feature_type: 'essential',
          complexity: 'medium',
          display_order: 1
        },
        {
          feature_id: 'product_catalog',
          name: 'Product Catalog',
          description: 'Browse and search products with categories',
          feature_type: 'essential',
          complexity: 'medium',
          display_order: 2
        },
        {
          feature_id: 'shopping_cart',
          name: 'Shopping Cart',
          description: 'Add products to cart and manage quantities',
          feature_type: 'essential',
          complexity: 'medium',
          display_order: 3
        },
        {
          feature_id: 'payment_processing',
          name: 'Payment Processing',
          description: 'Secure payment integration with Stripe/PayPal',
          feature_type: 'essential',
          complexity: 'high',
          display_order: 4
        },
        {
          feature_id: 'inventory_management',
          name: 'Inventory Management',
          description: 'Track stock levels and manage inventory',
          feature_type: 'suggested',
          complexity: 'high',
          display_order: 5
        }
      ]
    },
    {
      type: 'business_crm',
      title: 'CRM System',
      description: 'Customer relationship management, sales pipeline, lead tracking',
      icon: '👥',
      gradient: 'from-purple-50 to-purple-100',
      border: 'border-purple-200',
      text: 'text-purple-900',
      subtext: 'text-purple-700',
      features: [
        {
          feature_id: 'lead_management',
          name: 'Lead Management',
          description: 'Capture, track and manage sales leads',
          feature_type: 'essential',
          complexity: 'medium',
          display_order: 1
        },
        {
          feature_id: 'sales_pipeline',
          name: 'Sales Pipeline',
          description: 'Visual sales pipeline with drag-and-drop functionality',
          feature_type: 'essential',
          complexity: 'high',
          display_order: 2
        },
        {
          feature_id: 'customer_analytics',
          name: 'Customer Analytics',
          description: 'Detailed analytics and reporting on customer behavior',
          feature_type: 'suggested',
          complexity: 'medium',
          display_order: 3
        },
        {
          feature_id: 'communication_tools',
          name: 'Communication Tools',
          description: 'Email integration and communication tracking',
          feature_type: 'suggested',
          complexity: 'medium',
          display_order: 4
        }
      ]
    }
  ],
  'Technology & Analytics': [
    {
      type: 'analytics_dashboard',
      title: 'Analytics Dashboard',
      description: 'Data visualization, business intelligence, custom reports',
      icon: '📊',
      gradient: 'from-blue-50 to-blue-100',
      border: 'border-blue-200',
      text: 'text-blue-900',
      subtext: 'text-blue-700',
      features: [
        {
          feature_id: 'data_visualization',
          name: 'Data Visualization',
          description: 'Interactive charts and graphs',
          feature_type: 'essential',
          complexity: 'high',
          display_order: 1
        },
        {
          feature_id: 'custom_reports',
          name: 'Custom Reports',
          description: 'Generate and schedule custom reports',
          feature_type: 'essential',
          complexity: 'medium',
          display_order: 2
        }
      ]
    },
    {
      type: 'ai_chatbot_platform',
      title: 'AI Chatbot Platform',
      description: 'Deploy multi-channel AI chatbots with analytics and workflows',
      icon: '🤖',
      gradient: 'from-teal-50 to-teal-100',
      border: 'border-teal-200',
      text: 'text-teal-900',
      subtext: 'text-teal-700',
      features: [
        {
          feature_id: 'nlp_engine',
          name: 'NLP Engine',
          description: 'Natural language processing for intent and entity extraction',
          feature_type: 'essential',
          complexity: 'high',
          display_order: 1
        },
        {
          feature_id: 'channel_integrations',
          name: 'Channel Integrations',
          description: 'Integrate with web, WhatsApp, and Slack',
          feature_type: 'essential',
          complexity: 'medium',
          display_order: 2
        },
        {
          feature_id: 'conversation_analytics',
          name: 'Conversation Analytics',
          description: 'Track KPIs: containment rate, CSAT, and response time',
          feature_type: 'suggested',
          complexity: 'medium',
          display_order: 3
        }
      ]
    }
  ],
  'Custom & Others': [
    {
      type: 'custom_project',
      title: 'Custom Project',
      description: 'Describe your unique project requirements and let AI help design it',
      icon: '🎨',
      gradient: 'from-gray-50 to-gray-100',
      border: 'border-gray-200',
      text: 'text-gray-900',
      subtext: 'text-gray-700',
      features: []
    },
    {
      type: 'project_management_tool',
      title: 'Project Management Tool',
      description: 'Tasks, Kanban boards, sprints, and team collaboration',
      icon: '🗂️',
      gradient: 'from-amber-50 to-amber-100',
      border: 'border-amber-200',
      text: 'text-amber-900',
      subtext: 'text-amber-700',
      features: [
        {
          feature_id: 'kanban_boards',
          name: 'Kanban Boards',
          description: 'Organize tasks into customizable columns',
          feature_type: 'essential',
          complexity: 'medium',
          display_order: 1
        },
        {
          feature_id: 'sprint_planning',
          name: 'Sprint Planning',
          description: 'Plan sprints, track velocity, and manage backlogs',
          feature_type: 'essential',
          complexity: 'high',
          display_order: 2
        },
        {
          feature_id: 'collaboration_tools',
          name: 'Collaboration Tools',
          description: 'Comments, mentions, and notifications',
          feature_type: 'suggested',
          complexity: 'medium',
          display_order: 3
        }
      ]
    }
  ]
};

async function seedDatabase() {
  console.log('🌱 Starting Template Manager database seeding...');
  
  const client = await database.getClient();
  
  try {
    await client.query('BEGIN');
    
    // Clear existing data
    console.log('🧹 Clearing existing template data...');
    await client.query('DELETE FROM feature_usage');
    await client.query('DELETE FROM custom_features');
    await client.query('DELETE FROM template_features');
    await client.query('DELETE FROM templates WHERE type != \'_migration_test\'');
    
    let totalTemplates = 0;
    let totalFeatures = 0;
    
    // Seed templates by category
    for (const [category, templates] of Object.entries(TEMPLATE_DATA)) {
      console.log(`📂 Seeding category: ${category}`);
      
      for (const templateData of templates) {
        // Insert template
        const templateId = uuidv4();
        const templateQuery = `
          INSERT INTO templates (
            id, type, title, description, icon, category, 
            gradient, border, text, subtext
          ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
        `;
        
        await client.query(templateQuery, [
          templateId,
          templateData.type,
          templateData.title,
          templateData.description,
          templateData.icon,
          category,
          templateData.gradient,
          templateData.border,
          templateData.text,
          templateData.subtext
        ]);
        
        totalTemplates++;
        console.log(`  ✅ Template: ${templateData.title}`);
        
        // Insert features for this template
        for (const featureData of templateData.features) {
          const featureId = uuidv4();
          const featureQuery = `
            INSERT INTO template_features (
              id, template_id, feature_id, name, description, 
              feature_type, complexity, display_order, is_default
            ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
          `;
          
          await client.query(featureQuery, [
            featureId,
            templateId,
            featureData.feature_id,
            featureData.name,
            featureData.description,
            featureData.feature_type,
            featureData.complexity,
            featureData.display_order,
            true // is_default
          ]);
          
          totalFeatures++;
          console.log(`    🎯 Feature: ${featureData.name} (${featureData.feature_type})`);
        }
      }
    }
    
    // Add some sample usage data for demonstration
    console.log('📊 Adding sample usage data...');
    const sampleUsageQuery = `
      INSERT INTO feature_usage (template_id, feature_id, user_session, project_id)
      SELECT 
        t.id,
        tf.id,
        'demo_session_' || (RANDOM() * 100)::int,
        'demo_project_' || (RANDOM() * 50)::int
      FROM templates t
      JOIN template_features tf ON t.id = tf.template_id
      WHERE RANDOM() < 0.3  -- 30% of features get sample usage
    `;
    
    const usageResult = await client.query(sampleUsageQuery);
    
    // Update usage counts based on sample data
    const updateUsageQuery = `
      UPDATE template_features 
      SET usage_count = (
        SELECT COUNT(*) 
        FROM feature_usage 
        WHERE feature_id = template_features.id
      )
    `;
    
    await client.query(updateUsageQuery);
    
    await client.query('COMMIT');
    
    console.log('✅ Database seeding completed successfully!');
    console.log(`📊 Summary:`);
    console.log(`   - Templates created: ${totalTemplates}`);
    console.log(`   - Features created: ${totalFeatures}`);
    console.log(`   - Sample usage records: ${usageResult.rowCount}`);
    console.log(`   - Categories: ${Object.keys(TEMPLATE_DATA).length}`);
    
  } catch (error) {
    await client.query('ROLLBACK');
    console.error('❌ Database seeding failed:', error.message);
    throw error;
  } finally {
    client.release();
  }
}

// Run seeder if called directly
if (require.main === module) {
  seedDatabase()
    .then(() => {
      console.log('🎉 Seeding process completed!');
      process.exit(0);
    })
    .catch((error) => {
      console.error('💥 Seeding process failed:', error.message);
      process.exit(1);
    });
}

module.exports = { seedDatabase };