class ServerRegistrationService {
    constructor(supabase, logger) {
        this.supabase = supabase;
        this.logger = logger;
        this.logger.info('ServerRegistrationService initialized');
    }

    async registerServer(guildId, serverName) {
        // Input validation
        if (!guildId || typeof guildId !== 'string') {
            throw new Error('Invalid guildId provided');
        }
        if (!serverName || typeof serverName !== 'string') {
            throw new Error('Invalid serverName provided');
        }

        this.logger.info('registerServer method called', { 
            guildId, 
            serverName,
            timestamp: new Date().toISOString() 
        });

        try {
            // Check if server exists
            const { data: existingServer, error: checkError } = await this.supabase
                .from('servers')
                .select('*')
                .eq('discord_server_id', guildId)
                .single();

            this.logger.debug('Database query result', {
                hasExistingServer: !!existingServer,
                hasError: !!checkError,
                errorCode: checkError?.code
            });

            // If server exists, update the name if it changed
            if (existingServer) {
                if (existingServer.server_name !== serverName) {
                    const { data: updatedServer, error: updateError } = await this.supabase
                        .from('servers')
                        .update({ server_name: serverName })
                        .eq('id', existingServer.id)
                        .select()
                        .single();

                    if (updateError) {
                        this.logger.error('Failed to update server name', { error: updateError });
                        throw updateError;
                    }

                    this.logger.info('Server name updated', {
                        serverId: updatedServer.id,
                        oldName: existingServer.server_name,
                        newName: serverName
                    });
                    return { status: 'updated', server: updatedServer };
                }
                
                return { status: 'exists', server: existingServer };
            }

            // Create new server if it doesn't exist
            const { data: newServer, error: insertError } = await this.supabase
                .from('servers')
                .insert([{
                    discord_server_id: guildId,
                    server_name: serverName,
                    active: true,
                    created_at: new Date().toISOString()
                }])
                .select()
                .single();

            if (insertError) {
                this.logger.error('Failed to insert new server', { 
                    error: insertError,
                    details: insertError.details 
                });
                throw insertError;
            }

            this.logger.info('New server created successfully', {
                serverId: newServer.id,
                guildId,
                serverName
            });
            return { status: 'created', server: newServer };

        } catch (error) {
            this.logger.error('Error in registerServer:', {
                error: error.message,
                stack: error.stack,
                guildId,
                serverName
            });
            throw error;
        }
    }

    // Helper method to validate server data
    validateServerData(guildId, serverName) {
        if (!guildId || typeof guildId !== 'string') {
            return { valid: false, error: 'Invalid guildId' };
        }
        if (!serverName || typeof serverName !== 'string') {
            return { valid: false, error: 'Invalid serverName' };
        }
        if (serverName.length > 100) {
            return { valid: false, error: 'Server name too long' };
        }
        return { valid: true };
    }
}

module.exports = ServerRegistrationService;