const db = require('../database');
const { getMinecraftServers } = require('../panel/discovery');
const { writeWhitelistFile } = require('../panel/files');
const { reloadWhitelistCommand } = require('../panel/commands');

async function triggerImmediateSync(retryOnly = false) {
  console.log(retryOnly ? "--- Starting Retry Sync (failed servers only) ---" : "--- Starting Whitelist Sync ---");
  try {
    // 1. Fetch Players (Now includes 'lifetime' for the Trinity)
    const { rows: players, rowCount: playerCount } = await db.query(
      `SELECT minecraft_username as name, minecraft_uuid as uuid 
       FROM users 
       JOIN subscriptions ON users.discord_id = subscriptions.discord_id 
       WHERE subscriptions.status IN ('active', 'grace_period', 'lifetime')`
    );
    console.log(`[Sync] Retrieved ${playerCount} active players from database.`);

    // 2. Fetch Servers
    let servers = await getMinecraftServers();
    
    // If retry mode, only sync servers that previously failed
    if (retryOnly) {
      const { rows: failedServers } = await db.query(
        `SELECT server_identifier FROM server_sync_log WHERE is_online = false`
      );
      const failedIds = failedServers.map(s => s.server_identifier);
      servers = servers.filter(s => failedIds.includes(s.identifier));
      console.log(`[Sync] Retrying ${servers.length} previously failed servers.`);
    } else {
      console.log(`[Sync] Discovered ${servers.length} target servers.`);
    }

    if (servers.length === 0) {
      if (retryOnly) {
        console.log("[Sync] No failed servers to retry.");
      } else {
        console.warn("[Sync] WARN: 0 servers discovered. Check MINECRAFT_NEST_IDS in .env.");
      }
      return { successCount: 0, failCount: 0 };
    }

    // 3. Process Servers Sequentially
    let successCount = 0;
    let failCount = 0;

    for (const server of servers) {
      try {
        await writeWhitelistFile(server.identifier, players);
        await reloadWhitelistCommand(server.identifier);
        
        await db.query(
          "INSERT INTO server_sync_log (server_identifier, last_successful_sync, is_online, last_error) VALUES ($1, NOW(), true, NULL) ON CONFLICT (server_identifier) DO UPDATE SET last_successful_sync = NOW(), is_online = true, last_error = NULL",
          [server.identifier]
        );
        successCount++;
        if (retryOnly) {
          console.log(`[Sync] ✅ Retry succeeded for ${server.name}`);
        }
      } catch (err) {
        console.error(`[Sync] ❌ Failed for server ${server.name} (${server.identifier}):`, err.message);
        await db.query(
          "INSERT INTO server_sync_log (server_identifier, last_error, is_online) VALUES ($1, $2, false) ON CONFLICT (server_identifier) DO UPDATE SET last_error = $2, is_online = false",
          [server.identifier, err.message]
        );
        failCount++;
      }
    }
    
    console.log(`[Sync] Complete. Success: ${successCount}, Failed: ${failCount}`);
    console.log("-------------------------------");
    return { successCount, failCount };
  } catch (error) {
    console.error("[Sync] Critical failure during execution:", error);
    return { successCount: 0, failCount: 0 };
  }
}

module.exports = { triggerImmediateSync };
