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

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

  async findAll() {
    return this.prisma.theme.findMany({
      orderBy: { sortOrder: 'asc' },
    });
  }

  async findOne(id: number) {
    return this.prisma.theme.findUnique({
      where: { id },
      include: {
        courses: {
          where: { status: 'PUBLISHED' },
          select: { id: true, name: true, coverImagePath: true },
          take: 5,
        },
      },
    });
  }

  async create(data: { name: string; description?: string; sortOrder?: number }) {
    const maxSortOrder = await this.prisma.theme.aggregate({
      _max: { sortOrder: true },
    });

    return this.prisma.theme.create({
      data: {
        name: data.name,
        description: data.description,
        sortOrder: data.sortOrder ?? (maxSortOrder._max.sortOrder || 0) + 1,
      },
    });
  }

  async update(id: number, data: { name?: string; description?: string; sortOrder?: number; status?: string }) {
    return this.prisma.theme.update({
      where: { id },
      data,
    });
  }

  async remove(id: number) {
    // 检查是否有关联课程
    const courseCount = await this.prisma.course.count({
      where: { themeId: id },
    });

    if (courseCount > 0) {
      throw new Error(`该主题下有 ${courseCount} 个课程包，无法删除`);
    }

    return this.prisma.theme.delete({
      where: { id },
    });
  }

  async reorder(ids: number[]) {
    const updates = ids.map((id, index) =>
      this.prisma.theme.update({
        where: { id },
        data: { sortOrder: index + 1 },
      }),
    );

    return Promise.all(updates);
  }
}
