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

@Injectable()
export class AdminStatsService {
  constructor(private prisma: PrismaService) {}

  async getStats() {
    const [
      tenantCount,
      activeTenantCount,
      courseCount,
      publishedCourseCount,
      studentCount,
      teacherCount,
      lessonCount,
      monthlyLessons,
    ] = await Promise.all([
      this.prisma.tenant.count(),
      this.prisma.tenant.count({ where: { status: 'ACTIVE' } }),
      this.prisma.course.count(),
      this.prisma.course.count({ where: { status: 'PUBLISHED' } }),
      this.prisma.student.count(),
      this.prisma.teacher.count(),
      this.prisma.lesson.count(),
      this.getThisMonthLessonCount(),
    ]);

    return {
      tenantCount,
      activeTenantCount,
      courseCount,
      publishedCourseCount,
      studentCount,
      teacherCount,
      lessonCount,
      monthlyLessons,
    };
  }

  private async getThisMonthLessonCount() {
    const now = new Date();
    const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);

    return this.prisma.lesson.count({
      where: {
        createdAt: {
          gte: firstDayOfMonth,
        },
      },
    });
  }

  async getTrendData() {
    // Get last 6 months data
    const months: Array<{ month: string; tenantCount: number; lessonCount: number; studentCount: number }> = [];

    for (let i = 5; i >= 0; i--) {
      const date = new Date();
      date.setMonth(date.getMonth() - i);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const monthStr = `${year}-${String(month).padStart(2, '0')}`;

      const firstDay = new Date(year, month - 1, 1);
      const lastDay = new Date(year, month, 0, 23, 59, 59);

      const [tenantCount, lessonCount, studentCount] = await Promise.all([
        this.prisma.tenant.count({
          where: {
            createdAt: {
              lte: lastDay,
            },
          },
        }),
        this.prisma.lesson.count({
          where: {
            createdAt: {
              gte: firstDay,
              lte: lastDay,
            },
          },
        }),
        this.prisma.student.count({
          where: {
            createdAt: {
              lte: lastDay,
            },
          },
        }),
      ]);

      months.push({
        month: monthStr,
        tenantCount,
        lessonCount,
        studentCount,
      });
    }

    return months;
  }

  async getActiveTenants(limit: number = 5) {
    // Get tenants with most lessons in the last 30 days
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const tenants = await this.prisma.tenant.findMany({
      select: {
        id: true,
        name: true,
        teacherCount: true,
        studentCount: true,
        _count: {
          select: {
            lessons: {
              where: {
                createdAt: {
                  gte: thirtyDaysAgo,
                },
              },
            },
          },
        },
      },
      orderBy: {
        lessons: {
          _count: 'desc',
        },
      },
      take: limit,
    });

    return tenants.map((t) => ({
      id: t.id,
      name: t.name,
      lessonCount: t._count.lessons,
      teacherCount: t.teacherCount,
      studentCount: t.studentCount,
    }));
  }

  async getPopularCourses(limit: number = 5) {
    // Get courses with most usage
    const courses = await this.prisma.course.findMany({
      select: {
        id: true,
        name: true,
        usageCount: true,
        teacherCount: true,
      },
      where: {
        status: 'PUBLISHED',
      },
      orderBy: {
        usageCount: 'desc',
      },
      take: limit,
    });

    return courses;
  }

  async getRecentActivities(limit: number = 10) {
    const activities: Array<{
      id: number;
      type: string;
      title: string;
      description?: string;
      time: Date;
    }> = [];

    // Get recent lessons
    const recentLessons = await this.prisma.lesson.findMany({
      select: {
        id: true,
        createdAt: true,
        tenant: {
          select: {
            name: true,
          },
        },
        course: {
          select: {
            name: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
      take: limit,
    });

    for (const lesson of recentLessons) {
      activities.push({
        id: lesson.id,
        type: 'lesson',
        title: `${lesson.tenant.name} 完成了课程《${lesson.course.name}》`,
        time: lesson.createdAt,
      });
    }

    // Get recent tenants
    const recentTenants = await this.prisma.tenant.findMany({
      select: {
        id: true,
        name: true,
        createdAt: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
      take: limit,
    });

    for (const tenant of recentTenants) {
      activities.push({
        id: tenant.id + 10000,
        type: 'tenant',
        title: `新租户注册: ${tenant.name}`,
        time: tenant.createdAt,
      });
    }

    // Sort by time and limit
    return activities
      .sort((a, b) => b.time.getTime() - a.time.getTime())
      .slice(0, limit)
      .map((a) => ({
        ...a,
        time: a.time.toISOString(),
      }));
  }
}
