// trainer.service.ts (add method)
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Course } from '../course/course.entity';

@Injectable()
export class TrainerService {
  constructor(@InjectRepository(Course) private coursesRepo: Repository<Course>) { }

  async getTrainerCoursesWithContent(trainerId: number, skip = 0, take = 20) {
    const [rows, total] = await this.coursesRepo.findAndCount({
      where: { trainer: { id: trainerId } as any },
      relations: { lessons: { steps: true }, trainer: true },
      order: { id: 'DESC' },
      skip, take,
    });

    // sanitize + sort steps
    const items = rows.map(c => ({
      id: c.id,
      title: c.title,
      description: c.description,
      duration: c.duration,
      price: c.price,
      discountPrice: c.discountPrice,
      level: c.level,
      isPublished: c.isPublished,
      publishStatus: c.publishStatus,
      ratingAvg: c.ratingAvg,
      ratingCount: c.ratingCount,
      courseImage: c.courseImage ? process.env.APP_BASE_URL + c.courseImage : null,
      courseVideo: c.courseVideo ? process.env.APP_BASE_URL + c.courseVideo : null,
      lessons: (c.lessons || []).map(l => ({
        id: l.id,
        title: l.title,
        description: l.description,
        steps: (l.steps || []).sort((a, b) => a.order - b.order).map(s => ({
          id: s.id,
          type: s.type,
          title: s.title,
          order: s.order,
          content: s.content,
          teleprompterText: s.teleprompterText,
          videoUrl: (s as any).videoPath ?? null,
          questionData: s.questionData,
        })),
      })),
    }));

    return { total, items };
  }

  async getTrainerCourseById(trainerId: number, courseId: number) {
    const course = await this.coursesRepo.findOne({
      where: { id: courseId, trainer: { id: trainerId } as any },
      relations: { lessons: { steps: true }, trainer: true },
    });
    if (!course) throw new NotFoundException('Course not found');

    // sanitize + sort steps
    const items = (course.lessons || []).map(l => ({
      id: l.id,
      title: l.title,
      description: l.description,
      steps: (l.steps || []).sort((a, b) => a.order - b.order).map(s => ({
        id: s.id,
        type: s.type,
        title: s.title,
        order: s.order,
        content: s.content,
        teleprompterText: s.teleprompterText,
        videoUrl: (s as any).videoPath ?? null,
        questionData: s.questionData,
      })),
    }));

    return { course: { ...course, lessons: items } };
  }
}
