import { Injectable, ForbiddenException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Lesson } from './lesson.entity';
import { Course } from '../course/course.entity';
import { UpdateLessonDto } from './dto/update-lesson.dto';
import { CreateLessonDto } from './dto/create-lesson.dto';
import { User } from '../users/user.entity';

@Injectable()
export class LessonsService {
  constructor(
    @InjectRepository(Lesson) private lessonRepo: Repository<Lesson>,
    @InjectRepository(Course) private courseRepo: Repository<Course>,
  ) { }

  async createLesson(courseId: number, dto: CreateLessonDto) {
    const course = await this.courseRepo.findOne({ where: { id: courseId } });
    if (!course) throw new Error('Course not found');

    const lesson = this.lessonRepo.create({ ...dto, course });
    return this.lessonRepo.save(lesson);
  }

  async getLessons(courseId: number) {
    return this.lessonRepo.find({
      where: { course: { id: courseId } }, relations: ['steps'], order: {
        id: 'ASC',            // lesson order
        steps: { order: 'ASC' } // steps order
      }
    });
  }
  async updateLesson(courseId: number, lessonId: number, dto: UpdateLessonDto, user: User) {
    const lesson = await this.lessonRepo.findOne({
      where: { id: lessonId, course: { id: courseId } },
      relations: ['course', 'course.trainer'],
    });
    if (!lesson) throw new NotFoundException('Lesson not found');
    if (user.role !== 'admin' && lesson.course.trainer.id !== user.id) {
      throw new ForbiddenException('You can only update lessons of your courses');
    }
    Object.assign(lesson, dto);
    return this.lessonRepo.save(lesson);
  }

  async deleteLesson(courseId: number, lessonId: number, user: User) {
    const lesson = await this.lessonRepo.findOne({
      where: { id: lessonId, course: { id: courseId } },
      relations: ['course', 'course.trainer'],
    });
    if (!lesson) throw new NotFoundException('Lesson not found');
    if (user.role !== 'admin' && lesson.course.trainer.id !== user.id) {
      throw new ForbiddenException('You can only delete lessons of your courses');
    }
    // CASCADE will remove steps
    await this.lessonRepo.delete(lessonId);
    return { message: 'Lesson deleted' };
  }
}
