import { BadRequestException, NotFoundException } from '@nestjs/common';
import { ClassesService } from './classes.service';

function createService(classRepo: Record<string, jest.Mock>, classTeacherRepo = {}) {
  return new ClassesService(
    classRepo as never,
    {} as never,
    classTeacherRepo as never,
    {} as never,
    {} as never,
    {} as never,
    {} as never,
    {} as never,
  );
}

describe('ClassesService — archive and teacher boundaries', () => {
  it('rejects repeated archive and restore operations', async () => {
    await expect(
      createService({ findOne: jest.fn().mockResolvedValue({ isArchived: true }) }).archive(1),
    ).rejects.toBeInstanceOf(BadRequestException);
    await expect(
      createService({ findOne: jest.fn().mockResolvedValue({ isArchived: false }) }).restore(1),
    ).rejects.toBeInstanceOf(BadRequestException);
  });

  it('rejects assigning a teacher to a missing class', async () => {
    const classTeacherRepo = { findOne: jest.fn(), create: jest.fn(), save: jest.fn() };
    await expect(
      createService({ findOne: jest.fn().mockResolvedValue(null) }, classTeacherRepo).addTeacher(
        9,
        {
          userId: 2,
          roleType: 'head_teacher',
        },
      ),
    ).rejects.toBeInstanceOf(NotFoundException);
    expect(classTeacherRepo.save).not.toHaveBeenCalled();
  });

  it('rejects duplicate teacher roles', async () => {
    const classTeacherRepo = {
      findOne: jest.fn().mockResolvedValue({ id: 3 }),
      create: jest.fn(),
      save: jest.fn(),
    };
    await expect(
      createService(
        { findOne: jest.fn().mockResolvedValue({ id: 1 }) },
        classTeacherRepo,
      ).addTeacher(1, {
        userId: 2,
        roleType: 'head_teacher',
      }),
    ).rejects.toBeInstanceOf(BadRequestException);
  });

  it('rejects removing a teacher or assignment that is not in the class', async () => {
    const classTeacherRepo = {
      find: jest.fn().mockResolvedValue([]),
      findOne: jest.fn().mockResolvedValue(null),
      delete: jest.fn(),
    };
    const service = createService({}, classTeacherRepo);
    await expect(service.removeTeacher(1, 2)).rejects.toBeInstanceOf(NotFoundException);
    await expect(service.removeTeacherAssignment(1, 3)).rejects.toBeInstanceOf(NotFoundException);
    expect(classTeacherRepo.delete).not.toHaveBeenCalled();
  });
});
