import { db, EnrollmentStatus, PostType } from "@nice/common";

// 更新课程评价统计
export async function updateCourseReviewStats(courseId: string) {
    const reviews = await db.post.findMany({
        where: {
            courseId,
            type: PostType.COURSE_REVIEW,
            deletedAt: null
        },
        select: { rating: true }
    });
    const numberOfReviews = reviews.length;
    const averageRating = numberOfReviews > 0
        ? reviews.reduce((sum, review) => sum + review.rating, 0) / numberOfReviews
        : 0;

    return db.course.update({
        where: { id: courseId },
        data: { numberOfReviews, averageRating }
    });
}

// 更新课程注册统计
export async function updateCourseEnrollmentStats(courseId: string) {
    const completedEnrollments = await db.enrollment.count({
        where: {
            courseId,
            status: EnrollmentStatus.COMPLETED
        }
    });
    const totalEnrollments = await db.enrollment.count({
        where: { courseId }
    });
    const completionRate = totalEnrollments > 0
        ? (completedEnrollments / totalEnrollments) * 100
        : 0;
    return db.course.update({
        where: { id: courseId },
        data: {
            numberOfStudents: totalEnrollments,
            completionRate
        }
    });
}

