import { CoreDataWarehouse } from '../models/CoreDataWarehouse';
import { DataSyncConfig, DataSyncResult } from '../shared/types/shared/DataAbstractionLayer';
import { schedule, ScheduledTask } from 'node-cron';
import { EnhancedDataSource } from '../shared/types/shared/DataAbstractionLayer';
import { dataAbstractionLayerService } from './DataAbstractionLayerService';

export class DataSyncService {
  private syncTasks: Map<string, ScheduledTask> = new Map();
  private syncConfigs: Map<string, DataSyncConfig> = new Map();

  async initialize(): Promise<void> {
    // 加载同步配置
    await this.loadSyncConfigs();
    // 启动所有同步任务
    this.startAllSyncTasks();
  }

  async loadSyncConfigs(): Promise<void> {
    // 这里可以从数据库或配置文件加载同步配置
    // 暂时使用硬编码的配置
    const defaultConfigs: DataSyncConfig[] = [
      {
        id: 'sync-product-data',
        dataSource: 'productDataSource',
        schedule: '0 */1 * * *', // 每小时同步一次
        enabled: true,
        lastSync: 0,
        nextSync: Date.now() + 60 * 60 * 1000,
        syncStatus: 'pending',
      },
      {
        id: 'sync-order-data',
        dataSource: 'orderDataSource',
        schedule: '*/15 * * * *', // 每15分钟同步一次
        enabled: true,
        lastSync: 0,
        nextSync: Date.now() + 15 * 60 * 1000,
        syncStatus: 'pending',
      },
      {
        id: 'sync-customer-data',
        dataSource: 'customerDataSource',
        schedule: '0 */6 * * *', // 每6小时同步一次
        enabled: true,
        lastSync: 0,
        nextSync: Date.now() + 6 * 60 * 60 * 1000,
        syncStatus: 'pending',
      },
    ];

    for (const config of defaultConfigs) {
      this.syncConfigs.set(config.id, config);
    }
  }

  startAllSyncTasks(): void {
    for (const [id, config] of this.syncConfigs.entries()) {
      if (config.enabled) {
        this.startSyncTask(id, config);
      }
    }
  }

  startSyncTask(id: string, config: DataSyncConfig): void {
    const task = schedule(config.schedule, async () => {
      await this.executeSync(config);
    });

    this.syncTasks.set(id, task);
    console.log(`Started sync task for ${config.dataSource} with schedule ${config.schedule}`);
  }

  stopSyncTask(id: string): void {
    const task = this.syncTasks.get(id);
    if (task) {
      task.stop();
      this.syncTasks.delete(id);
      console.log(`Stopped sync task: ${id}`);
    }
  }

  async executeSync(config: DataSyncConfig): Promise<DataSyncResult> {
    const startTime = Date.now();
    let recordsSynced = 0;
    let error: string | undefined;

    try {
      // 更新同步状态
      config.syncStatus = 'running';
      this.syncConfigs.set(config.id, config);

      // 获取数据源
      const dataSource = dataAbstractionLayerService.getDataSource(config.dataSource);
      if (!dataSource) {
        throw new Error(`DataSource ${config.dataSource} not found`);
      }

      // 从数据源获取数据
      const data = await dataSource.list();
      recordsSynced = data.length;

      // 存储到核心数据仓库
      for (const item of data) {
        await this.storeDataToWarehouse(config.dataSource, item);
      }

      // 更新同步状态
      config.syncStatus = 'completed';
      config.lastSync = Date.now();
      config.nextSync = this.calculateNextSync(config.schedule);
      config.error = undefined;

      console.log(`Sync completed for ${config.dataSource}: ${recordsSynced} records`);
    } catch (err) {
      error = err instanceof Error ? err.message : 'Unknown error';
      config.syncStatus = 'failed';
      config.error = error;
      console.error(`Sync failed for ${config.dataSource}: ${error}`);
    } finally {
      this.syncConfigs.set(config.id, config);
    }

    return {
      success: config.syncStatus === 'completed',
      dataSource: config.dataSource,
      recordsSynced,
      duration: Date.now() - startTime,
      error,
      timestamp: Date.now(),
    };
  }

  async storeDataToWarehouse(dataSource: string, data: any): Promise<void> {
    const dataId = data.id || this.generateDataId(data);
    const dataType = this.getDataFileType(data);

    try {
      await CoreDataWarehouse.upsert({
        dataType,
        dataId,
        data: JSON.stringify(data),
        sourceSystem: dataSource,
        syncStatus: 'synced',
        lastSyncAt: new Date(),
        nextSyncAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 默认24小时后再次同步
        metadata: JSON.stringify({ 
          lastModified: data.updatedAt || data.modifiedAt || new Date(),
          source: dataSource,
        }),
      });
    } catch (error) {
      console.error('Failed to store data to warehouse:', error);
      throw error;
    }
  }

  private generateDataId(data: any): string {
    // 生成唯一的数据ID
    return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }

  private getDataFileType(data: any): string {
    // 根据数据结构判断数据类型
    if (data.sku || data.productId) {
      return 'product';
    } else if (data.orderId || data.invoiceId) {
      return 'order';
    } else if (data.customerId || data.email) {
      return 'customer';
    } else if (data.platform || data.storeId) {
      return 'platform';
    } else {
      return 'general';
    }
  }

  private calculateNextSync(schedule: string): number {
    // 简单实现：根据cron表达式计算下次同步时间
    // 这里可以使用更复杂的cron解析库
    return Date.now() + 60 * 60 * 1000; // 默认1小时后
  }

  async getSyncStatus(dataSource?: string): Promise<DataSyncConfig[]> {
    if (dataSource) {
      const config = Array.from(this.syncConfigs.values()).find(c => c.dataSource === dataSource);
      return config ? [config] : [];
    }
    return Array.from(this.syncConfigs.values());
  }

  async manuallyTriggerSync(dataSource: string): Promise<DataSyncResult> {
    const config = Array.from(this.syncConfigs.values()).find(c => c.dataSource === dataSource);
    if (!config) {
      throw new Error(`No sync config found for dataSource: ${dataSource}`);
    }

    return this.executeSync(config);
  }
}

export const dataSyncService = new DataSyncService();
