import { Injectable, Optional } from '@nestjs/common';
import { PrismaService } from '../../infrastructure/database/prisma.service';
import { RedisService } from '../../infrastructure/redis/redis.service';

const CACHE_KEY = 'admin:dashboard:stats';
const CACHE_TTL = 120; // 2 min

@Injectable()
export class AdminDashboardService {
  constructor(
    private readonly prisma: PrismaService,
    @Optional() private readonly redis?: RedisService,
  ) {}

  async getStats() {
    // Try cache first
    if (this.redis) {
      try {
        const cached = await this.redis.get(CACHE_KEY);
        if (cached) return JSON.parse(cached);
      } catch {}
    }

    const today = new Date(); today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today); tomorrow.setDate(tomorrow.getDate() + 1);
    const weekAgo = new Date(Date.now() - 7 * 86400000);

    const [
      totalUsers, newUsersToday, activeUsersToday,
      totalKnowledgeBases, newKbsToday,
      totalFiles, totalStorageBytes,
      todayImportCount, failedImportCount,
      todayAiCalls, todayAiCost,
      failedTasks,
      upcomingExpirations,
    ] = await Promise.all([
      this.prisma.user.count({ where: { deletedAt: null } }).catch(() => 0),
      this.prisma.user.count({ where: { createdAt: { gte: today, lt: tomorrow }, deletedAt: null } }).catch(() => 0),
      this.prisma.user.count({ where: { lastLoginAt: { gte: today, lt: tomorrow }, deletedAt: null } }).catch(() => 0),
      this.prisma.knowledgeBase.count({ where: { deletedAt: null } }).catch(() => 0),
      this.prisma.knowledgeBase.count({ where: { createdAt: { gte: today, lt: tomorrow }, deletedAt: null } }).catch(() => 0),
      this.prisma.uploadedFile.count().catch(() => 0),
      this.prisma.uploadedFile.aggregate({ _sum: { sizeBytes: true } }).then(r => Number(r._sum.sizeBytes ?? 0)).catch(() => 0),
      this.prisma.documentImport.count({ where: { createdAt: { gte: today, lt: tomorrow } } }).catch(() => 0),
      this.prisma.documentImport.count({ where: { status: 'failed' } }).catch(() => 0),
      this.prisma.aiUsageLog.count({ where: { createdAt: { gte: today, lt: tomorrow } } }).catch(() => 0),
      this.prisma.costDailySummary.aggregate({ where: { date: { gte: today, lt: tomorrow } }, _sum: { cost: true } }).then(r => Number(r._sum.cost ?? 0)).catch(() => 0),
      this.prisma.taskLog.count({ where: { status: 'failed', createdAt: { gte: weekAgo } } }).catch(() => 0),
      this.prisma.secretRecord.count({ where: { expiresAt: { lte: new Date(Date.now() + 30 * 86400000), gt: new Date() } } }).catch(() => 0),
    ]);

    const result = {
      totalUsers, newUsersToday, activeUsersToday,
      totalKnowledgeBases, newKbsToday,
      totalFiles, totalStorageBytes,
      todayImportCount, failedImportCount,
      todayAiCalls, todayAiCost: Math.round(todayAiCost * 100) / 100,
      failedTasks,
      upcomingExpirations,
      userTrend: [] as { date: string; value: number }[],
      aiCallTrend: [] as { date: string; value: number }[],
      serverSummary: null,
    };

    // Cache result
    if (this.redis) {
      try { await this.redis.set(CACHE_KEY, JSON.stringify(result), CACHE_TTL); } catch {}
    }

    return result;
  }

  async refreshCache() {
    if (this.redis) {
      try { await this.redis.del(CACHE_KEY); } catch {}
    }
    return this.getStats();
  }
}
