import { BadRequestException } from '@nestjs/common';
import { ClassroomsService } from './classrooms.service';

describe('ClassroomsService.purge', () => {
  const createService = (overrides?: {
    classroom?: Record<string, unknown>;
    scheduleCount?: number;
    rentalCount?: number;
    deviceCount?: number;
  }) => {
    const classroom = { id: 1, name: '101教室', status: 'archived', ...overrides?.classroom };
    const repo = {
      findOne: jest.fn().mockResolvedValue(classroom),
      delete: jest.fn().mockResolvedValue({ affected: 1 }),
    };
    const scheduleRepo = { count: jest.fn().mockResolvedValue(overrides?.scheduleCount ?? 0) };
    const rentalRepo = { count: jest.fn().mockResolvedValue(overrides?.rentalCount ?? 0) };
    const deviceRepo = { count: jest.fn().mockResolvedValue(overrides?.deviceCount ?? 0) };
    const service = new ClassroomsService(
      repo as never,
      rentalRepo as never,
      scheduleRepo as never,
      deviceRepo as never,
    );
    return { service, repo, scheduleRepo, rentalRepo, deviceRepo };
  };

  it('rejects classrooms that are not archived', async () => {
    const { service, repo } = createService({ classroom: { status: 'available' } });
    await expect(service.purge(1)).rejects.toThrow(
      new BadRequestException('仅已归档教室可以永久删除，请先归档'),
    );
    expect(repo.delete).not.toHaveBeenCalled();
  });

  it('rejects classrooms with schedules, rentals, or devices', async () => {
    const withSchedule = createService({ scheduleCount: 1 });
    await expect(withSchedule.service.purge(1)).rejects.toThrow(
      new BadRequestException('该教室存在排课记录，无法永久删除'),
    );

    const withRental = createService({ rentalCount: 1 });
    await expect(withRental.service.purge(1)).rejects.toThrow(
      new BadRequestException('该教室存在租赁订单，无法永久删除'),
    );

    const withDevice = createService({ deviceCount: 1 });
    await expect(withDevice.service.purge(1)).rejects.toThrow(
      new BadRequestException('该教室绑定了考勤机，无法永久删除'),
    );
    expect(withDevice.repo.delete).not.toHaveBeenCalled();
  });

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