const logger = require('../utils/logger');

class ServerRegistrationService {
  constructor(gameServerUrl, apiUrl, serverName, serverRegion, maxPlayers = 10) {
    this.gameServerUrl = gameServerUrl;
    this.apiUrl = apiUrl;
    this.serverName = serverName;
    this.serverRegion = serverRegion;
    this.maxPlayers = maxPlayers;
    this.serverId = `gameserver_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    this.registrationInterval = null;
    this.isRegistered = false;
    this.getCurrentPlayerCount = null; // Callback to get current player count
  }

  setPlayerCountCallback(callback) {
    this.getCurrentPlayerCount = callback;
  }

  async registerWithAPI() {
    try {
      logger.info(`[SERVER REGISTRATION] Registering server ${this.serverId} with API at ${this.apiUrl}`);
      
      const currentPlayers = this.getCurrentPlayerCount ? this.getCurrentPlayerCount() : 0;
      
      const serverData = {
        serverId: this.serverId,
        name: this.serverName,
        type: 'public',
        region: this.serverRegion,
        maxPlayers: this.maxPlayers,
        currentPlayers: currentPlayers,
        gameServerUrl: this.gameServerUrl,
        owner: {
          userId: 'system',
          username: 'Game Server'
        }
      };

      logger.info(`[SERVER REGISTRATION] Registering with ${currentPlayers} current players`);

      const response = await fetch(`${this.apiUrl}/api/servers/register`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(serverData)
      });

      if (response.ok) {
        const result = await response.json();
        logger.info(`[SERVER REGISTRATION] Server registered successfully:`, result);
        this.isRegistered = true;
        return true;
      } else {
        const error = await response.text();
        logger.error(`[SERVER REGISTRATION] Failed to register server: ${error}`);
        return false;
      }
    } catch (error) {
      logger.error(`[SERVER REGISTRATION] Error registering server:`, error);
      return false;
    }
  }

  async updateServerStatus(currentPlayers, status) {
    if (!this.isRegistered) {
      logger.warn(`[SERVER REGISTRATION] Cannot update status - server not registered`);
      return false;
    }

    try {
      logger.info(`[SERVER REGISTRATION] Updating server ${this.serverId} status:`, {
        currentPlayers,
        status
      });

      const response = await fetch(`${this.apiUrl}/api/servers/update-status/${this.serverId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ currentPlayers, status })
      });

      if (response.ok) {
        const result = await response.json();
        logger.info(`[SERVER REGISTRATION] Status updated successfully:`, result);
        return true;
      } else {
        const error = await response.text();
        logger.error(`[SERVER REGISTRATION] Failed to update status: ${error}`);
        return false;
      }
    } catch (error) {
      logger.error(`[SERVER REGISTRATION] Error updating server status:`, error);
      return false;
    }
  }

  async updatePlayerCount(playerCount) {
    return await this.updateServerStatus(playerCount, 'active');
  }

  startHeartbeat() {
    // Register immediately
    this.registerWithAPI();

    // Set up periodic registration updates (every 30 seconds)
    this.registrationInterval = setInterval(async () => {
      await this.registerWithAPI();
    }, 30000);

    logger.info(`[SERVER REGISTRATION] Heartbeat started for server ${this.serverId}`);
  }

  stopHeartbeat() {
    if (this.registrationInterval) {
      clearInterval(this.registrationInterval);
      this.registrationInterval = null;
      logger.info(`[SERVER REGISTRATION] Heartbeat stopped for server ${this.serverId}`);
    }
  }

  async unregisterWithAPI() {
    try {
      logger.info(`[SERVER REGISTRATION] Unregistering server ${this.serverId} from API at ${this.apiUrl}`);
      
      const response = await fetch(`${this.apiUrl}/api/servers/unregister/${this.serverId}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (response.ok) {
        const result = await response.json();
        logger.info(`[SERVER REGISTRATION] Server unregistered successfully:`, result);
        this.isRegistered = false;
        return true;
      } else {
        const error = await response.text();
        logger.error(`[SERVER REGISTRATION] Failed to unregister server: ${error}`);
        return false;
      }
    } catch (error) {
      logger.error(`[SERVER REGISTRATION] Error unregistering server:`, error);
      return false;
    }
  }

  getServerId() {
    return this.serverId;
  }

  isServerRegistered() {
    return this.isRegistered;
  }
}

module.exports = ServerRegistrationService;
