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

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

  // ==================== 课程管理 ====================

  async findAll(courseId: number) {
    return this.prisma.courseLesson.findMany({
      where: { courseId },
      include: {
        steps: {
          orderBy: { sortOrder: 'asc' },
        },
        _count: {
          select: { steps: true },
        },
      },
      orderBy: { sortOrder: 'asc' },
    });
  }

  async findOne(id: number) {
    return this.prisma.courseLesson.findUnique({
      where: { id },
      include: {
        steps: {
          orderBy: { sortOrder: 'asc' },
        },
        course: {
          select: {
            id: true,
            name: true,
            coverImagePath: true,
          },
        },
      },
    });
  }

  async findByType(courseId: number, lessonType: string) {
    return this.prisma.courseLesson.findUnique({
      where: {
        courseId_lessonType: { courseId, lessonType },
      },
      include: {
        steps: {
          orderBy: { sortOrder: 'asc' },
        },
      },
    });
  }

  async create(
    courseId: number,
    data: {
      lessonType: string;
      name: string;
      description?: string;
      duration?: number;
      videoPath?: string;
      videoName?: string;
      pptPath?: string;
      pptName?: string;
      pdfPath?: string;
      pdfName?: string;
      objectives?: string;
      preparation?: string;
      extension?: string;
      reflection?: string;
      assessmentData?: string;
      useTemplate?: boolean;
    },
  ) {
    // 检查是否已存在相同类型的课程
    const existing = await this.prisma.courseLesson.findUnique({
      where: {
        courseId_lessonType: { courseId, lessonType: data.lessonType },
      },
    });

    if (existing) {
      throw new Error(`该课程包已存在 ${data.lessonType} 类型的课程`);
    }

    // 获取最大排序号
    const maxSortOrder = await this.prisma.courseLesson.aggregate({
      where: { courseId },
      _max: { sortOrder: true },
    });

    const lesson = await this.prisma.courseLesson.create({
      data: {
        courseId,
        ...data,
        sortOrder: (maxSortOrder._max.sortOrder || 0) + 1,
      },
    });

    return lesson;
  }

  async update(
    id: number,
    data: {
      name?: string;
      description?: string;
      duration?: number;
      videoPath?: string;
      videoName?: string;
      pptPath?: string;
      pptName?: string;
      pdfPath?: string;
      pdfName?: string;
      objectives?: string;
      preparation?: string;
      extension?: string;
      reflection?: string;
      assessmentData?: string;
      useTemplate?: boolean;
    },
  ) {
    return this.prisma.courseLesson.update({
      where: { id },
      data,
    });
  }

  async delete(id: number) {
    const lesson = await this.prisma.courseLesson.findUnique({
      where: { id },
    });

    if (!lesson) {
      throw new Error('课程不存在');
    }

    await this.prisma.courseLesson.delete({
      where: { id },
    });

    return { success: true };
  }

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

    return Promise.all(updates);
  }

  // ==================== 教学环节管理 ====================

  async findSteps(lessonId: number) {
    return this.prisma.lessonStep.findMany({
      where: { lessonId },
      include: {
        stepResources: {
          include: {
            resource: true,
          },
        },
      },
      orderBy: { sortOrder: 'asc' },
    });
  }

  async createStep(
    lessonId: number,
    data: {
      name: string;
      content?: string;
      duration?: number;
      objective?: string;
      resourceIds?: number[];
    },
  ) {
    // 获取最大排序号
    const maxSortOrder = await this.prisma.lessonStep.aggregate({
      where: { lessonId },
      _max: { sortOrder: true },
    });

    const step = await this.prisma.lessonStep.create({
      data: {
        lessonId,
        name: data.name,
        content: data.content,
        duration: data.duration || 5,
        objective: data.objective,
        resourceIds: data.resourceIds ? JSON.stringify(data.resourceIds) : null,
        sortOrder: (maxSortOrder._max.sortOrder || 0) + 1,
      },
    });

    // 创建环节资源关联
    if (data.resourceIds && data.resourceIds.length > 0) {
      await this.prisma.lessonStepResource.createMany({
        data: data.resourceIds.map((resourceId, index) => ({
          stepId: step.id,
          resourceId,
          sortOrder: index,
        })),
      });
    }

    return this.prisma.lessonStep.findUnique({
      where: { id: step.id },
      include: {
        stepResources: {
          include: { resource: true },
        },
      },
    });
  }

  async updateStep(
    stepId: number,
    data: {
      name?: string;
      content?: string;
      duration?: number;
      objective?: string;
      resourceIds?: number[];
    },
  ) {
    const updateData: any = { ...data };
    if (data.resourceIds !== undefined) {
      updateData.resourceIds = JSON.stringify(data.resourceIds);

      // 删除旧的资源关联
      await this.prisma.lessonStepResource.deleteMany({
        where: { stepId },
      });

      // 创建新的资源关联
      if (data.resourceIds.length > 0) {
        await this.prisma.lessonStepResource.createMany({
          data: data.resourceIds.map((resourceId, index) => ({
            stepId,
            resourceId,
            sortOrder: index,
          })),
        });
      }
    }

    return this.prisma.lessonStep.update({
      where: { id: stepId },
      data: updateData,
      include: {
        stepResources: {
          include: { resource: true },
        },
      },
    });
  }

  async deleteStep(stepId: number) {
    return this.prisma.lessonStep.delete({
      where: { id: stepId },
    });
  }

  async reorderSteps(lessonId: number, stepIds: number[]) {
    const updates = stepIds.map((id, index) =>
      this.prisma.lessonStep.update({
        where: { id },
        data: { sortOrder: index + 1 },
      }),
    );

    return Promise.all(updates);
  }

  // ==================== 教师端查询 ====================

  async findCourseLessonsForTeacher(courseId: number, tenantId: number) {
    // 检查租户是否有权限访问该课程
    const tenantCourse = await this.prisma.tenantCourse.findFirst({
      where: { tenantId, courseId, authorized: true },
    });

    if (!tenantCourse) {
      // 检查是否通过套餐授权
      const tenantPackage = await this.prisma.tenantPackage.findFirst({
        where: {
          tenantId,
          status: 'ACTIVE',
          package: {
            courses: {
              some: { courseId },
            },
          },
        },
      });

      if (!tenantPackage) {
        throw new Error('无权访问该课程');
      }
    }

    return this.findAll(courseId);
  }
}
