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

@Injectable()
export class ReportingService {
  private readonly logger = new Logger(ReportingService.name);

  constructor(private readonly prisma: PrismaService) {}

  /** Generate user growth report */
  async userReport(days = 30): Promise<string> {
    const since = new Date(Date.now() - days * 86400000);
    const users = await this.prisma.user.findMany({
      where: { createdAt: { gte: since }, deletedAt: null },
      orderBy: { createdAt: 'desc' },
      select: { id: true, email: true, nickname: true, role: true, status: true, createdAt: true, lastLoginAt: true },
    });

    const header = 'ID,邮箱,昵称,角色,状态,注册时间,最后登录';
    const rows = users.map(u =>
      [u.id, u.email || '', u.nickname || '', u.role, u.status, u.createdAt?.toISOString() || '', u.lastLoginAt?.toISOString() || ''].map(v => `"${v}"`).join(',')
    );
    return [header, ...rows].join('\n');
  }

  /** Generate learning stats report */
  async learningReport(days = 30): Promise<string> {
    const since = new Date(Date.now() - days * 86400000);
    const sessions = await this.prisma.learningSession.findMany({
      where: { startedAt: { gte: since } },
      orderBy: { startedAt: 'desc' },
      select: { id: true, userId: true, mode: true, status: true, startedAt: true, endedAt: true, durationSeconds: true },
    });

    const header = 'ID,用户ID,模式,状态,开始时间,结束时间,时长(秒)';
    const rows = sessions.map(s =>
      [s.id, s.userId, s.mode, s.status, s.startedAt?.toISOString() || '', s.endedAt?.toISOString() || '', String(s.durationSeconds || 0)].map(v => `"${v}"`).join(',')
    );
    return [header, ...rows].join('\n');
  }

  /** Generate review stats report */
  async reviewReport(days = 30): Promise<string> {
    const since = new Date(Date.now() - days * 86400000);
    const logs = await this.prisma.reviewLog.findMany({
      where: { reviewedAt: { gte: since } },
      orderBy: { reviewedAt: 'desc' },
      select: { id: true, userId: true, rating: true, responseText: true, reviewedAt: true },
    });

    const header = 'ID,用户ID,评分,回答,复习时间';
    const rows = logs.map(l =>
      [l.id, l.userId, l.rating, (l.responseText || '').slice(0, 100), l.reviewedAt?.toISOString() || ''].map(v => `"${v}"`).join(',')
    );
    return [header, ...rows].join('\n');
  }

  /** Get export job history */
  async getExportJobs(page = 1, limit = 20) {
    const take = Math.min(limit, 100);
    const skip = (Math.max(page, 1) - 1) * take;
    const [items, total] = await Promise.all([
      this.prisma.exportJob.findMany({ orderBy: { createdAt: 'desc' }, take, skip }),
      this.prisma.exportJob.count(),
    ]);
    return { items, total };
  }
}
