import { AppDataSource, SystemConfig, User, PlatformAccount, PublishTask } from '../models/index.js';
import type { SystemConfig as SystemConfigType } from '@media-manager/shared';
import { PLATFORM_TYPES } from '@media-manager/shared';
import { wsManager } from '../websocket/index.js';

interface UpdateConfigParams {
  allowRegistration?: boolean;
  defaultUserRole?: string;
}

interface SystemStatus {
  database: 'connected' | 'disconnected';
  redis: 'connected' | 'disconnected';
  onlineUsers: number;
  totalUsers: number;
  totalAccounts: number;
  totalTasks: number;
  uptime: number;
}

export class SystemService {
  private configRepository = AppDataSource.getRepository(SystemConfig);
  private userRepository = AppDataSource.getRepository(User);
  private accountRepository = AppDataSource.getRepository(PlatformAccount);
  private taskRepository = AppDataSource.getRepository(PublishTask);

  async getPublicConfig(): Promise<SystemConfigType> {
    const configs = await this.configRepository.find();
    const configMap = new Map(configs.map(c => [c.configKey, c.configValue]));

    return {
      allowRegistration: configMap.get('allow_registration') === 'true',
      defaultUserRole: configMap.get('default_user_role') || 'operator',
      maxUploadSize: 4096 * 1024 * 1024, // 4GB
      supportedPlatforms: PLATFORM_TYPES,
    };
  }

  async updateConfig(params: UpdateConfigParams): Promise<void> {
    if (params.allowRegistration !== undefined) {
      await this.setConfig('allow_registration', String(params.allowRegistration));
    }
    if (params.defaultUserRole) {
      await this.setConfig('default_user_role', params.defaultUserRole);
    }
  }

  async getSystemStatus(): Promise<SystemStatus> {
    const [totalUsers, totalAccounts, totalTasks] = await Promise.all([
      this.userRepository.count(),
      this.accountRepository.count(),
      this.taskRepository.count(),
    ]);

    return {
      database: AppDataSource.isInitialized ? 'connected' : 'disconnected',
      redis: 'connected', // TODO: 实际检查 Redis 连接状态
      onlineUsers: wsManager.getOnlineUserCount(),
      totalUsers,
      totalAccounts,
      totalTasks,
      uptime: process.uptime(),
    };
  }

  private async setConfig(key: string, value: string): Promise<void> {
    const existing = await this.configRepository.findOne({ where: { configKey: key } });
    if (existing) {
      await this.configRepository.update(existing.id, { configValue: value });
    } else {
      await this.configRepository.save({ configKey: key, configValue: value });
    }
  }
}
