import { Injectable, Inject } from '@nestjs/common';
import { USER_REPOSITORY, IUserRepository } from '../../domain/repositories/user.repository.interface';
import { TRANSACTION_REPOSITORY, ITransactionRepository } from '../../domain/repositories/transaction.repository.interface';
import { UserRole } from '../../domain/entities/user.entity';

@Injectable()
export class AdminDashboardService {
  constructor(
    @Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository,
    @Inject(TRANSACTION_REPOSITORY) private readonly txRepo: ITransactionRepository,
  ) {}

  async getStats() {
    const [activeUsers, totalUsers, issuerCount, volumeMetrics] = await Promise.all([
      this.userRepo.countByStatus('active'),
      this.userRepo.count(),
      this.userRepo.countByRole(UserRole.ISSUER),
      this.txRepo.getVolumeMetrics(),
    ]);

    return {
      totalVolume: volumeMetrics.totalVolume,
      totalAmount: volumeMetrics.totalAmount,
      activeUsers,
      totalUsers,
      issuerCount,
      systemHealth: '98.5',
    };
  }

  async getRealtimeTrades(page: number, limit: number) {
    const [items, total] = await this.txRepo.findPaginated(page, limit);

    return {
      items: items.map((tx) => ({
        time: tx.createdAt,
        type: tx.type,
        orderId: tx.id,
        amount: tx.amount,
        status: tx.status,
      })),
      total,
      page,
      limit,
    };
  }

  async getSystemHealth() {
    const services = [
      { name: 'API Gateway', status: 'healthy', latency: '12ms' },
      { name: 'Database', status: 'healthy', latency: '3ms' },
      { name: 'Redis Cache', status: 'healthy', latency: '1ms' },
      { name: 'Kafka MQ', status: 'healthy', latency: '5ms' },
      { name: 'Chain Indexer', status: 'healthy', latency: '45ms' },
    ];
    return { services };
  }
}
