import { Injectable } from '@nestjs/common';
import { BaseService } from '../base/base.service';
import {
  UserProfile,
  db,
  ObjectType,
  Prisma,
  InstructorRole,
} from '@nice/common';
@Injectable()
export class CourseService extends BaseService<Prisma.CourseDelegate> {
  constructor() {
    super(db, ObjectType.COURSE);
  }
  async create(
    args: Prisma.CourseCreateArgs,
    params?: { staff?: UserProfile }
  ) {
    return await db.$transaction(async tx => {
      const result = await super.create(args, { tx });
      if (params?.staff?.id) {
        await tx.courseInstructor.create({
          data: {
            instructorId: params.staff.id,
            courseId: result.id,
            role: InstructorRole.MAIN,
          }
        });
      }
      return result;
    }, {
      timeout: 10000 // 10 seconds
    });
  }
  async update(
    args: Prisma.CourseUpdateArgs,
    params?: { staff?: UserProfile }
  ) {
    return await db.$transaction(async tx => {
      const result = await super.update(args, { tx });
      return result;
    }, {
      timeout: 10000 // 10 seconds
    });
  }
  async removeInstructor(courseId: string, instructorId: string) {
    return await db.courseInstructor.delete({
      where: {
        courseId_instructorId: {
          courseId,
          instructorId,
        },
      },
    });
  }
  async addInstructor(params: {
    courseId: string;
    instructorId: string;
    role?: string;
    order?: number;
  }) {
    return await db.courseInstructor.create({
      data: {
        courseId: params.courseId,
        instructorId: params.instructorId,
        role: params.role || InstructorRole.ASSISTANT,
        order: params.order,
      },
    });
  }
  async getInstructors(courseId: string) {
    return await db.courseInstructor.findMany({
      where: { courseId },
      include: { instructor: true },
      orderBy: { order: 'asc' },
    });
  }
}
