const mysql = require('mysql2/promise');
require('dotenv').config();
const bcrypt = require('bcrypt');

const categories = [
  { name: 'Instagram', icon: 'instagram' },
  { name: 'Facebook', icon: 'facebook' },
  { name: 'Twitter', icon: 'twitter' },
  { name: 'YouTube', icon: 'youtube' },
  { name: 'TikTok', icon: 'tiktok' },
  { name: 'Spotify', icon: 'music' }
];

const services = [
  { category: 'Instagram', name: 'Instagram Followers', price: 2.5, min: 10, max: 10000, apiId: 'insta_followers' },
  { category: 'Instagram', name: 'Instagram Likes', price: 0.5, min: 10, max: 50000, apiId: 'insta_likes' },
  { category: 'Instagram', name: 'Instagram Comments', price: 1.0, min: 5, max: 5000, apiId: 'insta_comments' },
  { category: 'Instagram', name: 'Instagram Views', price: 0.1, min: 100, max: 100000, apiId: 'insta_views' },
  
  { category: 'Facebook', name: 'Facebook Followers', price: 2.0, min: 10, max: 10000, apiId: 'fb_followers' },
  { category: 'Facebook', name: 'Facebook Likes', price: 0.4, min: 10, max: 50000, apiId: 'fb_likes' },
  { category: 'Facebook', name: 'Facebook Shares', price: 1.5, min: 5, max: 5000, apiId: 'fb_shares' },
  { category: 'Facebook', name: 'Facebook Page Likes', price: 3.0, min: 10, max: 5000, apiId: 'fb_page_likes' },
  
  { category: 'Twitter', name: 'Twitter Followers', price: 2.5, min: 10, max: 10000, apiId: 'tw_followers' },
  { category: 'Twitter', name: 'Twitter Likes', price: 0.5, min: 10, max: 50000, apiId: 'tw_likes' },
  { category: 'Twitter', name: 'Twitter Retweets', price: 1.2, min: 5, max: 5000, apiId: 'tw_retweets' },
  { category: 'Twitter', name: 'Twitter Views', price: 0.15, min: 100, max: 100000, apiId: 'tw_views' },
  
  { category: 'YouTube', name: 'YouTube Subscribers', price: 5.0, min: 10, max: 10000, apiId: 'yt_subs' },
  { category: 'YouTube', name: 'YouTube Views', price: 1.0, min: 100, max: 100000, apiId: 'yt_views' },
  { category: 'YouTube', name: 'YouTube Likes', price: 2.0, min: 10, max: 50000, apiId: 'yt_likes' },
  { category: 'YouTube', name: 'YouTube Comments', price: 1.5, min: 5, max: 5000, apiId: 'yt_comments' },
  
  { category: 'TikTok', name: 'TikTok Followers', price: 2.0, min: 10, max: 10000, apiId: 'tiktok_followers' },
  { category: 'TikTok', name: 'TikTok Likes', price: 0.3, min: 10, max: 100000, apiId: 'tiktok_likes' },
  { category: 'TikTok', name: 'TikTok Views', price: 0.05, min: 100, max: 500000, apiId: 'tiktok_views' },
  { category: 'TikTok', name: 'TikTok Shares', price: 1.0, min: 5, max: 5000, apiId: 'tiktok_shares' },
  
  { category: 'Spotify', name: 'Spotify Followers', price: 3.0, min: 10, max: 10000, apiId: 'spotify_followers' },
  { category: 'Spotify', name: 'Spotify Plays', price: 0.8, min: 100, max: 100000, apiId: 'spotify_plays' },
  { category: 'Spotify', name: 'Spotify Saves', price: 1.5, min: 10, max: 50000, apiId: 'spotify_saves' }
];

async function seedData() {
  let connection;
  try {
    connection = await mysql.createConnection({
      host: process.env.DB_HOST || 'localhost',
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || '',
      database: process.env.DB_NAME || 'wakatraffic'
    });

    console.log('✅ Connected to MySQL\n');

    // 1. Create admin user
    console.log('👤 Creating admin account...');
    const adminPassword = await bcrypt.hash('Admin@123', 10);
    try {
      const adminResult = await connection.execute(
        `INSERT INTO users (username, email, password_hash, first_name, last_name, role, balance, status) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
        ['admin', 'admin@wakatraffic.ng', adminPassword, 'Admin', 'User', 'admin', 0, 'active']
      );
      console.log('✅ Admin account created (ID: ' + adminResult[0].insertId + ')\n');
    } catch (err) {
      console.log('⚠️  Admin account already exists\n');
    }

    // 2. Create categories
    console.log('📂 Creating categories...');
    const categoryMap = {};
    for (const cat of categories) {
      try {
        const catResult = await connection.execute(
          `INSERT INTO categories (name, status) VALUES (?, ?)`,
          [cat.name, 'active']
        );
        categoryMap[cat.name] = catResult[0].insertId;
        console.log('  ✅ ' + cat.name);
      } catch (err) {
        if (err.message.includes('Duplicate')) {
          // Get existing category ID
          const [existing] = await connection.execute('SELECT id FROM categories WHERE name = ?', [cat.name]);
          if (existing.length > 0) {
            categoryMap[cat.name] = existing[0].id;
            console.log('  ℹ️  ' + cat.name + ' (exists)');
          }
        }
      }
    }

    // 3. Create API provider (Owlet)
    console.log('\n🔑 Creating API provider...');
    let providerId;
    try {
      const providerResult = await connection.execute(
        `INSERT INTO api_providers (name, api_url, api_key, status) VALUES (?, ?, ?, ?)`,
        ['Owlet Panel', 'https://owletpanel.com/api/v2', 'test-owlet', 'active']
      );
      providerId = providerResult[0].insertId;
      console.log('✅ Owlet API provider added (ID: ' + providerId + ')');
    } catch (err) {
      if (err.message.includes('Duplicate')) {
        const [existing] = await connection.execute('SELECT id FROM api_providers WHERE name = ?', ['Owlet Panel']);
        providerId = existing[0].id;
        console.log('ℹ️  Owlet provider already exists (ID: ' + providerId + ')');
      }
    }

    // 4. Add services
    console.log('\n📦 Creating services...');
    let serviceCount = 0;
    for (const svc of services) {
      try {
        await connection.execute(
          `INSERT INTO services (category_id, name, description, price, min_quantity, max_quantity, api_provider_id, api_service_id, status) 
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
          [
            categoryMap[svc.category],
            svc.name,
            'High-quality ' + svc.name.toLowerCase() + ' service',
            svc.price,
            svc.min,
            svc.max,
            providerId,
            svc.apiId,
            'active'
          ]
        );
        console.log('  ✅ ' + svc.name);
        serviceCount++;
      } catch (err) {
        console.log('  ⚠️  ' + svc.name + ': ' + err.message.substring(0, 40));
      }
    }

    console.log('\n' + '='.repeat(50));
    console.log('🎉 Seed completed!');
    console.log('='.repeat(50));
    console.log('📊 Summary:');
    console.log('  - Categories: ' + Object.keys(categoryMap).length);
    console.log('  - Services: ' + serviceCount);
    console.log('  - API Provider: Owlet Panel (test-owlet)');
    console.log('  - Admin: admin@wakatraffic.ng / Admin@123');
    console.log('\n');

    process.exit(0);
  } catch (error) {
    console.error('❌ Error:', error.message);
    process.exit(1);
  } finally {
    if (connection) await connection.end();
  }
}

seedData();
