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

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

  async getStats(userId: number) {
    const user = await this.prisma.user.findUnique({
      where: { id: userId, deletedAt: null },
      select: {
        nickname: true,
        avatar: true,
        memberPlan: true,
        memberExpire: true,
        sandboxDaily: true,
        createdAt: true,
      },
    });
    if (!user) throw new NotFoundException('用户不存在');

    const learnRecords = await this.prisma.learnRecord.findMany({
      where: { userId },
      select: { courseId: true, completed: true },
    });

    const courseIds = [...new Set(learnRecords.map(r => r.courseId))];
    const completedCount = learnRecords.filter(r => r.completed).length;
    const inProgressCourses = courseIds.length;

    const favoriteCount = await this.prisma.promptFavorite.count({ where: { userId } });

    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const todayCount = await this.prisma.learnRecord.count({
      where: { userId, updatedAt: { gte: today } },
    });

    const firstRecord = await this.prisma.learnRecord.findFirst({
      where: { userId },
      orderBy: { createdAt: 'asc' },
      select: { createdAt: true },
    });

    const studyDays = firstRecord
      ? Math.max(1, Math.ceil((Date.now() - firstRecord.createdAt.getTime()) / 86400000))
      : 0;

    return {
      user: {
        nickname: user.nickname,
        avatar: user.avatar,
        memberPlan: user.memberPlan,
        memberExpire: user.memberExpire,
        sandboxDaily: user.sandboxDaily,
        joinedAt: user.createdAt,
      },
      stats: {
        inProgressCourses,
        completedLessons: completedCount,
        favoritePrompts: favoriteCount,
        studyDays,
        todayLearned: todayCount,
      },
    };
  }

  async getProgress(userId: number) {
    const learnRecords = await this.prisma.learnRecord.findMany({
      where: { userId },
      include: {
        course: { select: { id: true, title: true, cover: true } },
        lesson: { select: { id: true, title: true } },
      },
      orderBy: { updatedAt: 'desc' },
    });

    const courseMap = new Map<number, { course: any; lessons: any[]; completedCount: number; totalCount: number }>();

    for (const record of learnRecords) {
      if (!courseMap.has(record.courseId)) {
        const totalLessons = await this.prisma.lesson.count({
          where: { chapter: { courseId: record.courseId } },
        });
        courseMap.set(record.courseId, {
          course: record.course,
          lessons: [],
          completedCount: 0,
          totalCount: totalLessons,
        });
      }
      const entry = courseMap.get(record.courseId)!;
      entry.lessons.push({
        id: record.lesson.id,
        title: record.lesson.title,
        completed: record.completed,
        progress: record.progress,
        updatedAt: record.updatedAt,
      });
      if (record.completed) entry.completedCount++;
    }

    const courses = Array.from(courseMap.values()).map(entry => ({
      course: entry.course,
      progress: entry.totalCount > 0 ? Math.round((entry.completedCount / entry.totalCount) * 100) : 0,
      completedCount: entry.completedCount,
      totalCount: entry.totalCount,
      recentLessons: entry.lessons.slice(0, 5),
    }));

    const recentRecords = learnRecords.slice(0, 10).map(r => ({
      lessonId: r.lesson.id,
      lessonTitle: r.lesson.title,
      courseId: r.course.id,
      courseTitle: r.course.title,
      completed: r.completed,
      progress: r.progress,
      updatedAt: r.updatedAt,
    }));

    return { courses, recentRecords };
  }

  async getFavorites(userId: number) {
    const favorites = await this.prisma.promptFavorite.findMany({
      where: { userId },
      include: {
        prompt: {
          select: {
            id: true,
            title: true,
            description: true,
            model: true,
            viewCount: true,
            likeCount: true,
            createdAt: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
    });

    return favorites.map(f => ({
      id: f.id,
      promptId: f.prompt.id,
      title: f.prompt.title,
      description: f.prompt.description,
      model: f.prompt.model,
      viewCount: f.prompt.viewCount,
      likeCount: f.prompt.likeCount,
      favoritedAt: f.createdAt,
    }));
  }

  async getProfile(userId: number) {
    const user = await this.prisma.user.findUnique({
      where: { id: userId, deletedAt: null },
      select: {
        id: true,
        phone: true,
        email: true,
        nickname: true,
        avatar: true,
        status: true,
        memberPlan: true,
        memberExpire: true,
        sandboxDaily: true,
        createdAt: true,
      },
    });
    if (!user) throw new NotFoundException('用户不存在');
    return user;
  }

  async updateProfile(userId: number, data: { nickname?: string; avatar?: string }) {
    const user = await this.prisma.user.findUnique({
      where: { id: userId, deletedAt: null },
    });
    if (!user) throw new NotFoundException('用户不存在');

    return this.prisma.user.update({
      where: { id: userId },
      data: {
        ...(data.nickname !== undefined && { nickname: data.nickname }),
        ...(data.avatar !== undefined && { avatar: data.avatar }),
      },
      select: {
        id: true,
        phone: true,
        email: true,
        nickname: true,
        avatar: true,
        status: true,
        memberPlan: true,
        memberExpire: true,
        sandboxDaily: true,
        createdAt: true,
      },
    });
  }
}
