using System.Text;

namespace Firefly
{
    public partial class Firefly
    {
        #region Server Operations
        /// <summary>
        /// Handles the AUTH command which authenticates a client.
        /// </summary>
        /// <param name="password">The password to authenticate with</param>
        /// <param name="clientId">The client ID</param>
        /// <returns>OK on success, error if authentication fails</returns>
        static byte[] HandleAuthCommand(string password, string clientId)
        {
            if (string.IsNullOrEmpty(serverPassword))
            {
                Console.WriteLine("AUTH command received but server has no password set");
                return Encoding.UTF8.GetBytes("-ERR this server does not require authentication\r\n");
            }

            if (serverPassword == password)
            {
                Console.WriteLine($"Client {clientId} successfully authenticated");
                authenticatedClients[clientId] = true;
                return Encoding.UTF8.GetBytes("+OK\r\n");
            }
            
            Console.WriteLine($"Client {clientId} failed authentication attempt with password: {password}");
            return Encoding.UTF8.GetBytes("-ERR invalid password\r\n");
        }

        /// <summary>
        /// Checks if a client is authenticated.
        /// </summary>
        /// <param name="clientId">The client ID</param>
        /// <returns>True if the client is authenticated, false otherwise</returns>
        static bool IsAuthenticated(string clientId)
        {
            // If no password is set, all clients are authenticated by default
            if (string.IsNullOrEmpty(serverPassword))
            {
                return true;
            }
            
            return authenticatedClients.TryGetValue(clientId, out bool authenticated) && authenticated;
        }

        /// <summary>
        /// Handles the SAVE command which triggers a manual backup of the data.
        /// </summary>
        static byte[] HandleSaveCommand()
        {
            try
            {
                BackupData();
                return Encoding.UTF8.GetBytes("+OK\r\n");
            }
            catch (Exception ex)
            {
                return Encoding.UTF8.GetBytes($"-ERR save failed: {ex.Message}\r\n");
            }
        }

        /// <summary>
        /// Handles the BGSAVE command which triggers an asynchronous backup of the data.
        /// </summary>
        static byte[] HandleBgSaveCommand()
        {
            // Start backup in a separate task
            Task.Run(() => BackupData());
            return Encoding.UTF8.GetBytes("+Background saving started\r\n");
        }

        /// <summary>
        /// Handles server shutdown operations
        /// </summary>
        static async Task ShutdownServer()
        {
            if (backupsEnabled)
            {
                Console.WriteLine("Performing final backup before shutdown...");
                await Task.Run(() => BackupData());
            }

            // Clean up any remaining client connections
            foreach (var clientId in authenticatedClients.Keys.ToList())
            {
                authenticatedClients.Remove(clientId);
            }

            Console.WriteLine("Server shutdown complete.");
        }
        #endregion
    }
} 