/**
 * 云服务器API控制器
 * 提供云服务器购买、续费、管理的REST API接口
 */

import { Request, Response } from 'express';
import { cloudServiceManager } from '../services/cloud-service';
import { cloudRemoteServiceManager } from '../services/cloud-remote-service';

interface CreateInstanceRequest {
  name: string;
  provider: 'aliyun' | 'tencent';
  region: string;
  instanceType: string;
  imageId: string;
  securityGroupId: string;
  vSwitchId: string;
  password?: string;
  keyPairName?: string;
  systemDiskSize: number;
  dataDiskSize?: number;
  tags?: Record<string, string>;
  billingType: 'prepaid' | 'postpaid';
  period?: number; // 预付费时长（月）
}

interface RenewInstanceRequest {
  instanceId: string;
  period: number;
}

interface RemoteSessionRequest {
  instanceId: string;
  user?: string;
}

/**
 * 获取云服务商列表
 */
export const getProviders = async (req: Request, res: Response) => {
  try {
    const providers = cloudServiceManager.getSupportedProviders();
    res.json({
      success: true,
      data: providers
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '获取服务商列表失败'
    });
  }
};

/**
 * 获取地域列表
 */
export const getRegions = async (req: Request, res: Response) => {
  try {
    const { provider } = req.params;
    const cloudProvider = cloudServiceManager.getProvider(provider, 'default');
    
    if (!cloudProvider) {
      return res.status(400).json({
        success: false,
        error: '不支持的云服务商'
      });
    }
    
    const result = await cloudProvider.listRegions();
    
    if (result.success) {
      res.json({
        success: true,
        data: result.data
      });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '获取地域列表失败'
    });
  }
};

/**
 * 获取实例规格列表
 */
export const getInstanceTypes = async (req: Request, res: Response) => {
  try {
    const { provider, region } = req.params;
    const cloudProvider = cloudServiceManager.getProvider(provider, region);
    
    if (!cloudProvider) {
      return res.status(400).json({
        success: false,
        error: '不支持的云服务商或地域'
      });
    }
    
    const result = await cloudProvider.listInstanceTypes();
    
    if (result.success) {
      res.json({
        success: true,
        data: result.data
      });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '获取实例规格失败'
    });
  }
};

/**
 * 获取镜像列表
 */
export const getImages = async (req: Request, res: Response) => {
  try {
    const { provider, region } = req.params;
    const cloudProvider = cloudServiceManager.getProvider(provider, region);
    
    if (!cloudProvider) {
      return res.status(400).json({
        success: false,
        error: '不支持的云服务商或地域'
      });
    }
    
    const result = await cloudProvider.listImages();
    
    if (result.success) {
      res.json({
        success: true,
        data: result.data
      });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '获取镜像列表失败'
    });
  }
};

/**
 * 创建云服务器实例
 */
export const createInstance = async (req: Request, res: Response) => {
  try {
    const request: CreateInstanceRequest = req.body;
    
    // 验证必填字段
    if (!request.name || !request.provider || !request.region || !request.instanceType) {
      return res.status(400).json({
        success: false,
        error: '缺少必填字段'
      });
    }
    
    const cloudProvider = cloudServiceManager.getProvider(request.provider, request.region);
    
    if (!cloudProvider) {
      return res.status(400).json({
        success: false,
        error: '不支持的云服务商或地域'
      });
    }
    
    const createRequest = {
      name: request.name,
      instanceType: request.instanceType,
      imageId: request.imageId || 'ubuntu_20_04_x64_20G_alibase_20240220.vhd',
      securityGroupId: request.securityGroupId || 'sg-default',
      vSwitchId: request.vSwitchId || 'vsw-default',
      password: request.password,
      keyPairName: request.keyPairName,
      systemDiskSize: request.systemDiskSize || 40,
      dataDiskSize: request.dataDiskSize,
      tags: request.tags
    };
    
    const result = await cloudProvider.createInstance(createRequest);
    
    if (result.success) {
      res.json({
        success: true,
        data: result.data,
        message: '云服务器创建成功'
      });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '创建云服务器失败'
    });
  }
};

/**
 * 获取实例列表
 */
export const getInstances = async (req: Request, res: Response) => {
  try {
    const { provider, region } = req.query;
    
    if (provider && region) {
      // 获取特定服务商和地域的实例
      const cloudProvider = cloudServiceManager.getProvider(provider as string, region as string);
      
      if (!cloudProvider) {
        return res.status(400).json({
          success: false,
          error: '不支持的云服务商或地域'
        });
      }
      
      const result = await cloudProvider.listInstances();
      
      if (result.success) {
        res.json({
          success: true,
          data: result.data
        });
      } else {
        res.status(400).json(result);
      }
    } else {
      // 获取所有实例
      const allInstances = await cloudServiceManager.getAllInstances();
      res.json({
        success: true,
        data: allInstances
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '获取实例列表失败'
    });
  }
};

/**
 * 获取实例详情
 */
export const getInstance = async (req: Request, res: Response) => {
  try {
    const { instanceId } = req.params;
    const { provider, region } = req.query;
    
    if (!provider || !region) {
      return res.status(400).json({
        success: false,
        error: '需要提供provider和region参数'
      });
    }
    
    const cloudProvider = cloudServiceManager.getProvider(provider as string, region as string);
    
    if (!cloudProvider) {
      return res.status(400).json({
        success: false,
        error: '不支持的云服务商或地域'
      });
    }
    
    const result = await cloudProvider.getInstance(instanceId);
    
    if (result.success) {
      res.json({
        success: true,
        data: result.data
      });
    } else {
      res.status(404).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '获取实例详情失败'
    });
  }
};

/**
 * 启动实例
 */
export const startInstance = async (req: Request, res: Response) => {
  try {
    const { instanceId } = req.params;
    const { provider, region } = req.body;
    
    if (!provider || !region) {
      return res.status(400).json({
        success: false,
        error: '需要提供provider和region参数'
      });
    }
    
    const cloudProvider = cloudServiceManager.getProvider(provider, region);
    
    if (!cloudProvider) {
      return res.status(400).json({
        success: false,
        error: '不支持的云服务商或地域'
      });
    }
    
    const result = await cloudProvider.startInstance(instanceId);
    
    if (result.success) {
      res.json({
        success: true,
        message: '实例启动命令已发送'
      });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '启动实例失败'
    });
  }
};

/**
 * 停止实例
 */
export const stopInstance = async (req: Request, res: Response) => {
  try {
    const { instanceId } = req.params;
    const { provider, region } = req.body;
    
    if (!provider || !region) {
      return res.status(400).json({
        success: false,
        error: '需要提供provider和region参数'
      });
    }
    
    const cloudProvider = cloudServiceManager.getProvider(provider, region);
    
    if (!cloudProvider) {
      return res.status(400).json({
        success: false,
        error: '不支持的云服务商或地域'
      });
    }
    
    const result = await cloudProvider.stopInstance(instanceId);
    
    if (result.success) {
      res.json({
        success: true,
        message: '实例停止命令已发送'
      });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '停止实例失败'
    });
  }
};

/**
 * 重启实例
 */
export const rebootInstance = async (req: Request, res: Response) => {
  try {
    const { instanceId } = req.params;
    const { provider, region } = req.body;
    
    if (!provider || !region) {
      return res.status(400).json({
        success: false,
        error: '需要提供provider和region参数'
      });
    }
    
    const cloudProvider = cloudServiceManager.getProvider(provider, region);
    
    if (!cloudProvider) {
      return res.status(400).json({
        success: false,
        error: '不支持的云服务商或地域'
      });
    }
    
    const result = await cloudProvider.rebootInstance(instanceId);
    
    if (result.success) {
      res.json({
        success: true,
        message: '实例重启命令已发送'
      });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '重启实例失败'
    });
  }
};

/**
 * 续费实例
 */
export const renewInstance = async (req: Request, res: Response) => {
  try {
    const { instanceId } = req.params;
    const request: RenewInstanceRequest = req.body;
    
    if (!request.period) {
      return res.status(400).json({
        success: false,
        error: '需要提供续费时长'
      });
    }
    
    const { provider, region } = req.body;
    
    if (!provider || !region) {
      return res.status(400).json({
        success: false,
        error: '需要提供provider和region参数'
      });
    }
    
    const cloudProvider = cloudServiceManager.getProvider(provider, region);
    
    if (!cloudProvider) {
      return res.status(400).json({
        success: false,
        error: '不支持的云服务商或地域'
      });
    }
    
    const result = await cloudProvider.renewInstance(instanceId, request.period);
    
    if (result.success) {
      res.json({
        success: true,
        message: '实例续费成功'
      });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '续费实例失败'
    });
  }
};

/**
 * 删除实例
 */
export const deleteInstance = async (req: Request, res: Response) => {
  try {
    const { instanceId } = req.params;
    const { provider, region } = req.body;
    
    if (!provider || !region) {
      return res.status(400).json({
        success: false,
        error: '需要提供provider和region参数'
      });
    }
    
    const cloudProvider = cloudServiceManager.getProvider(provider, region);
    
    if (!cloudProvider) {
      return res.status(400).json({
        success: false,
        error: '不支持的云服务商或地域'
      });
    }
    
    const result = await cloudProvider.deleteInstance(instanceId);
    
    if (result.success) {
      res.json({
        success: true,
        message: '实例删除成功'
      });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '删除实例失败'
    });
  }
};

/**
 * 创建远程会话
 */
export const createRemoteSession = async (req: Request, res: Response) => {
  try {
    const request: RemoteSessionRequest = req.body;
    
    if (!request.instanceId) {
      return res.status(400).json({
        success: false,
        error: '需要提供instanceId参数'
      });
    }
    
    const { provider, region } = req.body;
    
    if (!provider || !region) {
      return res.status(400).json({
        success: false,
        error: '需要提供provider和region参数'
      });
    }
    
    const result = await cloudRemoteServiceManager.createRemoteSession(
      provider,
      region,
      request.instanceId,
      request.user || 'root'
    );
    
    if (result.success) {
      res.json(result);
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '创建远程会话失败'
    });
  }
};

/**
 * 执行远程命令
 */
export const executeRemoteCommand = async (req: Request, res: Response) => {
  try {
    const { sessionId } = req.params;
    const { command } = req.body;
    
    if (!command) {
      return res.status(400).json({
        success: false,
        error: '需要提供command参数'
      });
    }
    
    const result = await cloudRemoteServiceManager.executeRemoteCommand(sessionId, command);
    
    if (result.success) {
      res.json(result);
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '执行远程命令失败'
    });
  }
};

/**
 * 获取活跃会话列表
 */
export const getActiveSessions = async (req: Request, res: Response) => {
  try {
    const sessions = cloudRemoteServiceManager.getActiveSessions();
    res.json({
      success: true,
      data: sessions
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '获取会话列表失败'
    });
  }
};

/**
 * 关闭会话
 */
export const closeSession = async (req: Request, res: Response) => {
  try {
    const { sessionId } = req.params;
    
    const result = await cloudRemoteServiceManager.closeSession(sessionId);
    
    if (result.success) {
      res.json(result);
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '关闭会话失败'
    });
  }
};

/**
 * 获取实例监控数据
 */
export const getInstanceMetrics = async (req: Request, res: Response) => {
  try {
    const { instanceId } = req.params;
    const { provider, region, metrics } = req.query;
    
    if (!provider || !region) {
      return res.status(400).json({
        success: false,
        error: '需要提供provider和region参数'
      });
    }
    
    const cloudProvider = cloudServiceManager.getProvider(provider as string, region as string);
    
    if (!cloudProvider) {
      return res.status(400).json({
        success: false,
        error: '不支持的云服务商或地域'
      });
    }
    
    const metricsArray = metrics ? (metrics as string).split(',') : ['cpu', 'memory', 'disk'];
    
    const result = await cloudProvider.getInstanceMetrics(instanceId, metricsArray);
    
    if (result.success) {
      res.json({
        success: true,
        data: result.data
      });
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '获取监控数据失败'
    });
  }
};