import Response from '@/lib/response/Response.js';
import Environment from '@/lib/environment.js';
// 心跳服务已移除
import logger from '@/lib/logger.js';
import nedbCleanupService from '@/lib/services/NeDBCleanupService.js';

export default {
    // 获取当前服务器信息
    get: {

        // 获取所有活跃服务器
        '/servers/active': async () => {
            try {
                // 心跳服务已移除，返回当前服务器信息
                const activeServers = [{
                    server_id: Environment.name || process.env.SERVICE_ID || 'jimeng-free-api',
                    server_name: Environment.name || process.env.SERVICE_NAME || 'jimeng-free-api',
                    host: Environment.host || process.env.SERVER_HOST || '0.0.0.0',
                    port: Environment.port || parseInt(process.env.SERVER_PORT || '3302'),
                    is_active: true
                }];
                
                return new Response({
                    success: true,
                    data: activeServers,
                    total: activeServers.length
                });
            } catch (error) {
                logger.error('Failed to get active servers:', error);
                return new Response({
                    success: false,
                    error: error.message
                }, { statusCode: 500 });
            }
        },

        // 获取所有在线服务器（基于心跳超时检查）
        '/servers/online': async () => {
            try {
                // 心跳服务已移除，返回当前服务器信息
                const onlineServers = [{
                    server_id: Environment.name || process.env.SERVICE_ID || 'jimeng-free-api',
                    server_name: Environment.name || process.env.SERVICE_NAME || 'jimeng-free-api',
                    host: Environment.host || process.env.SERVER_HOST || '0.0.0.0',
                    port: Environment.port || parseInt(process.env.SERVER_PORT || '3302'),
                    is_active: true
                }];
                
                return new Response({
                    success: true,
                    data: onlineServers,
                    total: onlineServers.length
                });
            } catch (error) {
                logger.error('Failed to get online servers:', error);
                return new Response({
                    success: false,
                    error: error.message
                }, { statusCode: 500 });
            }
        },

        // 获取服务器状态统计
        '/servers/stats': async () => {
            try {
                // 心跳服务已移除，返回简单统计
                const result = { 
                    totalServers: 1, 
                    activeServers: 1, 
                    onlineServers: 1,
                    healthRate: '100%'
                };

                return new Response({
                    success: true,
                    data: result
                });
            } catch (error) {
                logger.error('Failed to get server stats:', error);
                return new Response({
                    success: false,
                    error: error.message
                }, { statusCode: 500 });
            }
        },

        // 获取特定服务器详情
        '/servers/:serverId': async (request) => {
            try {
                const serverId = request.params.serverId;
                // 心跳服务已移除，返回当前服务器信息
                const server = {
                    server_id: Environment.name || process.env.SERVICE_ID || 'jimeng-free-api',
                    server_name: Environment.name || process.env.SERVICE_NAME || 'jimeng-free-api',
                    host: Environment.host || process.env.SERVER_HOST || '0.0.0.0',
                    port: Environment.port || parseInt(process.env.SERVER_PORT || '3302'),
                    is_active: true,
                    isOnline: true
                };

                return new Response({
                    success: true,
                    data: server
                });
            } catch (error) {
                logger.error('Failed to get server details:', error);
                return new Response({
                    success: false,
                    error: error.message
                }, { statusCode: 500 });
            }
        },

        // 获取 NeDB 清理服务状态
        '/nedb/cleanup/status': async () => {
            try {
                const status = nedbCleanupService.getStatus();
                
                return new Response({
                    success: true,
                    data: {
                        isRunning: status.isRunning,
                        nextCleanup: status.nextCleanup ? new Date(status.nextCleanup).toISOString() : null,
                        timestamp: new Date().toISOString()
                    }
                });
            } catch (error) {
                logger.error('Failed to get NeDB cleanup status:', error);
                return new Response({
                    success: false,
                    error: error.message
                }, { statusCode: 500 });
            }
        }
    },

    post: {
        // 手动清理离线服务器
        '/servers/cleanup': async () => {
            try {
                // 心跳服务已移除，无需清理
                
                return new Response({
                    success: true,
                    message: 'Offline servers cleaned up successfully'
                });
            } catch (error) {
                logger.error('Failed to cleanup offline servers:', error);
                return new Response({
                    success: false,
                    error: error.message
                }, { statusCode: 500 });
            }
        },

        // 手动触发 NeDB 数据清理
        '/nedb/cleanup': async () => {
            try {
                const result = await nedbCleanupService.manualCleanup();
                
                return new Response({
                    success: true,
                    message: 'NeDB cleanup completed successfully',
                    data: {
                        expiredResults: result.expiredResults,
                        expiredTasks: result.expiredTasks,
                        timestamp: new Date().toISOString()
                    }
                });
            } catch (error) {
                logger.error('Failed to perform NeDB cleanup:', error);
                return new Response({
                    success: false,
                    error: error.message
                }, { statusCode: 500 });
            }
        },

        // 更新服务器心跳（为Python项目提供）
        '/servers/:serverId/heartbeat': async (request) => {
            try {
                const serverId = request.params.serverId;
                const currentTime = Math.floor(Date.now() / 1000);
                
                // 心跳服务已移除，返回成功响应以保持兼容性
                return new Response({
                    success: true,
                    message: 'Heartbeat service disabled (using NeDB local storage)',
                    data: {
                        server_id: serverId,
                        updated_at: currentTime,
                        is_active: true
                    }
                });
            } catch (error) {
                logger.error('Failed to update server heartbeat:', error);
                return new Response({
                    success: false,
                    error: error.message
                }, { statusCode: 500 });
            }
        }
    }
};