const mysql = require('mysql2');
const axios = require('axios');
require('dotenv').config();

const categoryMapping = {
  'instagram': 1,
  'facebook': 2,
  'twitter': 3,
  'youtube': 4,
  'tiktok': 5,
  'spotify': 6
};

async function fetchOwletServices() {
  try {
    console.log('📡 Connecting to Owlet API with test-owlet key...');
    
    const response = await axios.post(
      'https://owletpanel.com/api/v2',
      {
        key: 'test-owlet',
        action: 'services'
      },
      {
        timeout: 10000
      }
    );

    console.log('✅ Connected to Owlet API');
    
    if (response.data && response.data.data) {
      const services = response.data.data;
      console.log('Retrieved ' + services.length + ' services from Owlet');
      return services;
    } else {
      console.log('No services found. Using sample data.');
      return generateSampleServices();
    }
  } catch (error) {
    if (error.code === 'ECONNREFUSED') {
      console.log('Owlet API not accessible. Using sample data instead.');
      return generateSampleServices();
    }
    console.error('Error fetching from Owlet: ' + error.message);
    console.log('Using sample data instead.');
    return generateSampleServices();
  }
}

function generateSampleServices() {
  const platforms = [
    { name: 'instagram', category_id: 1, services: [
      { name: 'Instagram Followers', min: 10, max: 500000, rate: 2.5 },
      { name: 'Instagram Likes', min: 10, max: 100000, rate: 0.5 },
      { name: 'Instagram Comments', min: 5, max: 50000, rate: 1.0 },
      { name: 'Instagram Views', min: 100, max: 1000000, rate: 0.1 },
      { name: 'Instagram Shares', min: 10, max: 50000, rate: 1.5 },
      { name: 'Instagram Saves', min: 10, max: 50000, rate: 1.2 },
      { name: 'Instagram Profile Visits', min: 100, max: 500000, rate: 0.2 },
      { name: 'Instagram Story Views', min: 100, max: 1000000, rate: 0.08 }
    ]},
    { name: 'facebook', category_id: 2, services: [
      { name: 'Facebook Followers', min: 10, max: 500000, rate: 2.0 },
      { name: 'Facebook Likes', min: 10, max: 100000, rate: 0.4 },
      { name: 'Facebook Shares', min: 5, max: 50000, rate: 1.5 },
      { name: 'Facebook Page Likes', min: 10, max: 50000, rate: 3.0 },
      { name: 'Facebook Comments', min: 5, max: 50000, rate: 0.8 },
      { name: 'Facebook Post Views', min: 100, max: 1000000, rate: 0.15 },
      { name: 'Facebook Video Views', min: 100, max: 1000000, rate: 0.2 }
    ]},
    { name: 'twitter', category_id: 3, services: [
      { name: 'Twitter Followers', min: 10, max: 500000, rate: 2.5 },
      { name: 'Twitter Likes', min: 10, max: 100000, rate: 0.5 },
      { name: 'Twitter Retweets', min: 5, max: 50000, rate: 1.2 },
      { name: 'Twitter Views', min: 100, max: 1000000, rate: 0.15 },
      { name: 'Twitter Replies', min: 5, max: 50000, rate: 0.8 },
      { name: 'Twitter Profile Views', min: 100, max: 500000, rate: 0.1 }
    ]},
    { name: 'youtube', category_id: 4, services: [
      { name: 'YouTube Subscribers', min: 10, max: 500000, rate: 5.0 },
      { name: 'YouTube Views', min: 100, max: 1000000, rate: 1.0 },
      { name: 'YouTube Likes', min: 10, max: 100000, rate: 2.0 },
      { name: 'YouTube Comments', min: 5, max: 50000, rate: 1.5 },
      { name: 'YouTube Shares', min: 5, max: 50000, rate: 2.5 },
      { name: 'YouTube Watch Time', min: 100, max: 500000, rate: 0.5 }
    ]},
    { name: 'tiktok', category_id: 5, services: [
      { name: 'TikTok Followers', min: 10, max: 500000, rate: 2.0 },
      { name: 'TikTok Likes', min: 10, max: 1000000, rate: 0.3 },
      { name: 'TikTok Views', min: 100, max: 5000000, rate: 0.05 },
      { name: 'TikTok Shares', min: 5, max: 50000, rate: 1.0 },
      { name: 'TikTok Comments', min: 5, max: 50000, rate: 0.6 },
      { name: 'TikTok Downloads', min: 10, max: 100000, rate: 0.8 },
      { name: 'TikTok Favorites', min: 10, max: 100000, rate: 0.7 }
    ]},
    { name: 'spotify', category_id: 6, services: [
      { name: 'Spotify Followers', min: 10, max: 500000, rate: 3.0 },
      { name: 'Spotify Plays', min: 100, max: 1000000, rate: 0.8 },
      { name: 'Spotify Saves', min: 10, max: 100000, rate: 1.5 },
      { name: 'Spotify Shares', min: 5, max: 50000, rate: 1.2 },
      { name: 'Spotify Playlist Followers', min: 10, max: 50000, rate: 2.0 }
    ]}
  ];

  const result = [];
  platforms.forEach(function(platform) {
    platform.services.forEach(function(svc, idx) {
      result.push({
        service: platform.name + '_' + idx,
        name: svc.name,
        category: platform.name,
        category_id: platform.category_id,
        rate: svc.rate,
        min: svc.min,
        max: svc.max
      });
    });
  });

  return result;
}

async function insertServicesToDatabase(services) {
  const pool = mysql.createPool({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'wakatraffic',
    waitForConnections: true,
    connectionLimit: 5,
    queueLimit: 0
  });

  return new Promise(function(resolve, reject) {
    pool.getConnection(function(err, conn) {
      if (err) {
        console.error('Database connection error: ' + err.message);
        reject(err);
        return;
      }

      console.log('\nConnected to database');
      console.log('Inserting ' + services.length + ' services...\n');

      let processed = 0;
      let inserted = 0;
      let duplicates = 0;
      const categoryStats = {};

      services.forEach(function(service, index) {
        const categoryId = service.category_id || 1;
        const apiServiceId = service.service || (service.category + '_' + index);
        
        if (!categoryStats[categoryId]) categoryStats[categoryId] = 0;
        
        const query = 'INSERT INTO services (category_id, name, description, price, min_quantity, max_quantity, api_provider_id, api_service_id, status) VALUES (?, ?, ?, ?, ?, ?, 1, ?, \'active\') ON DUPLICATE KEY UPDATE name = name';
        
        conn.query(
          query,
          [
            categoryId,
            service.name,
            'Professional service delivery',
            service.rate,
            service.min,
            service.max,
            apiServiceId
          ],
          function(err, result) {
            processed++;
            
            if (err) {
              if (err.code === 'ER_DUP_ENTRY') {
                duplicates++;
              }
            } else {
              if (result.affectedRows > 0) {
                inserted++;
                categoryStats[categoryId]++;
              }
            }

            if (processed % 100 === 0) {
              process.stdout.write('Progress: ' + processed + '/' + services.length + '\n');
            }

            if (processed === services.length) {
              console.log('Progress: ' + processed + '/' + services.length);
              
              console.log('\nServices per category:');
              const categoryNames = { 1: 'Instagram', 2: 'Facebook', 3: 'Twitter', 4: 'YouTube', 5: 'TikTok', 6: 'Spotify' };
              
              for (const catId in categoryStats) {
                console.log('   ' + categoryNames[catId] + ': ' + categoryStats[catId]);
              }

              conn.query('SELECT COUNT(*) as total FROM services', function(err, results) {
                if (!err) {
                  console.log('\nTotal services in database: ' + results[0].total);
                }
                conn.release();
                pool.end();
                resolve({ inserted: inserted, duplicates: duplicates, total: processed });
              });
            }
          }
        );
      });
    });
  });
}

async function main() {
  console.log('WakaTraffic - Owlet Services Sync\n');

  try {
    const services = await fetchOwletServices();
    
    if (services.length === 0) {
      console.log('No services fetched. Exiting.');
      process.exit(1);
    }

    const result = await insertServicesToDatabase(services);

    console.log('\n=== SYNC COMPLETED ===');
    console.log('Inserted: ' + result.inserted);
    console.log('Duplicates: ' + result.duplicates);
    console.log('Processed: ' + result.total + '\n');

    process.exit(0);
  } catch (error) {
    console.error('Sync failed: ' + error.message);
    process.exit(1);
  }
}

main();
