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

describe('ClassesService.purge', () => {
  const createService = (overrides?: {
    cls?: Record<string, unknown>;
    counts?: Record<string, number>;
  }) => {
    const cls = { id: 1, name: '冲刺班', code: 'C1', isArchived: true, ...overrides?.cls };
    const repo = {
      findOne: jest.fn().mockResolvedValue(cls),
      delete: jest.fn().mockResolvedValue({ affected: 1 }),
    };
    const counts = overrides?.counts ?? {};
    const countFor = (key: string) => jest.fn().mockResolvedValue(counts[key] ?? 0);
    const service = new ClassesService(
      repo as never,
      { count: countFor('classStudent') } as never,
      { count: countFor('classTeacher') } as never,
      { count: countFor('schedule') } as never,
      { count: countFor('attendance') } as never,
      { count: countFor('session') } as never,
      {} as never,
      {} as never,
      {} as never,
      { count: countFor('exam') } as never,
    );
    return { service, repo };
  };

  it('rejects classes that are not archived', async () => {
    const { service, repo } = createService({ cls: { isArchived: false } });
    await expect(service.purge(1)).rejects.toThrow(
      new BadRequestException('仅已归档班级可以永久删除，请先归档'),
    );
    expect(repo.delete).not.toHaveBeenCalled();
  });

  it('rejects classes with students, teachers, schedules, exams, or attendance', async () => {
    const { service, repo } = createService({ counts: { classStudent: 1 } });
    await expect(service.purge(1)).rejects.toThrow(
      new BadRequestException('该班级存在关联数据（班级学生），无法永久删除'),
    );
    expect(repo.delete).not.toHaveBeenCalled();
  });

  it('deletes an archived class with no references', async () => {
    const { service, repo } = createService();
    await expect(service.purge(1)).resolves.toEqual({
      message: '已永久删除班级（不可恢复）',
    });
    expect(repo.delete).toHaveBeenCalledWith(1);
  });
});
