import { Request, Response } from 'express';
import { dataAbstractionLayerService } from '../../services/DataAbstractionLayerService';
import { dataSyncService } from '../../services/DataSyncService';
import { actionDataService } from '../../services/ActionDataService';

export class DataAbstractionController {
  // 获取优先级数据
  async getPrioritizedData(req: Request, res: Response): Promise<void> {
    try {
      const { actionType, taskId } = req.params;
      const params = req.query;

      if (!actionType || !taskId) {
        res.status(400).json({ error: 'actionType and taskId are required' });
        return;
      }

      const data = await dataAbstractionLayerService.getPrioritizedData(actionType, taskId, params as Record<string, any>);
      res.json(data);
    } catch (error) {
      console.error('Error getting prioritized data:', error);
      res.status(500).json({ error: 'Failed to get prioritized data' });
    }
  }

  // 获取动作数据
  async getActionData(req: Request, res: Response): Promise<void> {
    try {
      const { actionType, taskId } = req.params;
      const { dataSource, priority, startDate, endDate } = req.query;

      if (!actionType || !taskId) {
        res.status(400).json({ error: 'actionType and taskId are required' });
        return;
      }

      let data;
      if (priority) {
        data = await actionDataService.getActionDataByPriority(actionType, taskId, priority as string);
      } else {
        data = await actionDataService.getActionData(actionType, taskId, dataSource as string);
      }

      // 转换数据格式
      const formattedData = data.map(item => ({
        ...item.toJSON(),
        data: JSON.parse(item.data),
        metadata: JSON.parse(item.metadata),
      }));

      res.json(formattedData);
    } catch (error) {
      console.error('Error getting action data:', error);
      res.status(500).json({ error: 'Failed to get action data' });
    }
  }

  // 手动触发数据同步
  async triggerSync(req: Request, res: Response): Promise<void> {
    try {
      const { dataSource } = req.params;

      if (!dataSource) {
        res.status(400).json({ error: 'dataSource is required' });
        return;
      }

      const result = await dataSyncService.manuallyTriggerSync(dataSource);
      res.json(result);
    } catch (error) {
      console.error('Error triggering sync:', error);
      res.status(500).json({ error: 'Failed to trigger sync' });
    }
  }

  // 获取同步状态
  async getSyncStatus(req: Request, res: Response): Promise<void> {
    try {
      const { dataSource } = req.query;

      const status = await dataSyncService.getSyncStatus(dataSource as string);
      res.json(status);
    } catch (error) {
      console.error('Error getting sync status:', error);
      res.status(500).json({ error: 'Failed to get sync status' });
    }
  }

  // 清理过期数据
  async cleanupExpiredData(req: Request, res: Response): Promise<void> {
    try {
      const deleted = await actionDataService.cleanupExpiredData();
      res.json({ deleted });
    } catch (error) {
      console.error('Error cleaning up expired data:', error);
      res.status(500).json({ error: 'Failed to clean up expired data' });
    }
  }

  // 获取动作数据统计
  async getActionDataStats(req: Request, res: Response): Promise<void> {
    try {
      const { actionType } = req.query;

      const stats = await actionDataService.getActionDataStats(actionType as string);
      res.json(stats);
    } catch (error) {
      console.error('Error getting action data stats:', error);
      res.status(500).json({ error: 'Failed to get action data stats' });
    }
  }

  // 清除缓存
  async clearCache(req: Request, res: Response): Promise<void> {
    try {
      const { dataSource } = req.query;

      await dataAbstractionLayerService.clearCache(dataSource as string);
      res.json({ success: true });
    } catch (error) {
      console.error('Error clearing cache:', error);
      res.status(500).json({ error: 'Failed to clear cache' });
    }
  }
}

export const dataAbstractionController = new DataAbstractionController();
