import { Job } from 'bullmq';
import { Logger } from '@nestjs/common';
import { ObjectType } from '@nice/common';
// import {
//   updateCourseEnrollmentStats,
//   updateCourseReviewStats,
// } from '@server/models/course/utils';
import { QueueJobType } from '../types';
import {
  updateCourseEnrollmentStats,
  updateCourseReviewStats,
  updateParentLectureStats,
} from '@server/models/post/utils';
import {
  updatePostViewCount,
  updateTotalCourseViewCount,
} from '../models/post/utils';
const logger = new Logger('QueueWorker');
export default async function processJob(job: Job<any, any, QueueJobType>) {
  try {
    if (job.name === QueueJobType.UPDATE_STATS) {
      const { sectionId, courseId, type } = job.data;
      // 处理 section 统计
      if (sectionId) {
        await updateParentLectureStats(sectionId);
        logger.debug(`Updated section stats for sectionId: ${sectionId}`);
      }
      // 如果没有 courseId，提前返回
      if (!courseId) {
        return;
      }
      // 处理 course 相关统计
      switch (type) {
        case ObjectType.LECTURE:
          await updateParentLectureStats(courseId);
          break;
        case ObjectType.ENROLLMENT:
          await updateCourseEnrollmentStats(courseId);
          break;
        case ObjectType.POST:
          await updateCourseReviewStats(courseId);
          break;
        default:
          logger.warn(`Unknown update stats type: ${type}`);
      }

      logger.debug(
        `Updated course stats for courseId: ${courseId}, type: ${type}`,
      );
    }
    if (job.name === QueueJobType.UPDATE_POST_VISIT_COUNT) {
      await updatePostViewCount(job.data.id, job.data.type);
    }
    if (job.name === QueueJobType.UPDATE_POST_STATE) {
      await updatePostViewCount(job.data.id, job.data.type);
    }
    if (job.name === QueueJobType.UPDATE_TOTAL_COURSE_VIEW_COUNT) {
      await updateTotalCourseViewCount(job.data.type);
    }
  } catch (error: any) {
    logger.error(
      `Error processing stats update job: ${error.message}`,
      error.stack,
    );
  }
}
