import { readDB, writeDB, withDB } from '../db.js';
import { fetchPlayerInfo } from './garena.js';
import { normalizePackageId } from './pricing.js';

/**
 * Re-consulta Garena para UN solo usuario y actualiza users.json con los datos
 * frescos (nickname, paquetes, descuentos). Preserva purchasedPackages local.
 * @param {string} id - ID del jugador
 * @returns {{ status: string, updated: boolean, nickname?: string, discountedPackages?: string[] }}
 */
export async function refreshSingleUser(id) {
  const result = await fetchPlayerInfo(id);

  if (result.status !== 'ok') {
    return { status: result.status, updated: false };
  }

  // Write atómico bajo lock: re-lee dentro del lock y actualiza
  const updated = await withDB(freshDb => {
    const existing = freshDb.users[id] || {};

    freshDb.users[id] = {
      nickname: result.nickname,
      packages: result.packages,
      discountedPackages: result.packages
        .filter(p => p.hasDiscount)
        .map(p => normalizePackageId(p.id)),
      purchasedPackages: existing.purchasedPackages || [],
      cachedAt: new Date().toISOString(),
    };
    return true;
  });

  return {
    status: 'ok',
    updated,
    nickname: result.nickname,
    discountedPackages: result.packages.filter(p => p.hasDiscount).map(p => normalizePackageId(p.id)),
  };
}

/**
 * Actualiza los usuarios que no tienen nickname (por fallos de cookie).
 * Para cada usuario sin nickname intenta volver a consultar Garena usando la
 * cookie actual. Si la llamada es exitosa, actualiza el registro con nickname
 * y paquetes/discounts.
 * @returns {{updated: number}} número de usuarios actualizados.
 */
export async function updateMissingNicknames() {
  let initialDb = readDB();
  const users = initialDb.users || {};
  let updated = 0;

  // Procesar secuencialmente para evitar saturar Garena con peticiones simultáneas.
  for (const [id, user] of Object.entries(users)) {
    if (user.nickname) continue; // ya tiene nickname, saltar
    try {
      const result = await fetchPlayerInfo(id);
      if (result.status !== 'ok') continue; // sigue sin poder
      
      // Reload DB exactly before writing to avoid overwriting orders/users created during await
      const freshDb = readDB();
      
      const freshUser = {
        nickname: result.nickname,
        packages: result.packages,
        discountedPackages: result.packages.filter(p => p.hasDiscount).map(p => normalizePackageId(p.id)),
        purchasedPackages: (freshDb.users[id]?.purchasedPackages || []),
        cachedAt: new Date().toISOString(),
      };
      freshDb.users[id] = freshUser;
      writeDB(freshDb);
      updated++;
    } catch (_) {
      // Silenciar errores por usuario individual
    }
  }

  return { updated };
}
