import { BadRequestException } from '@nestjs/common';
import { OrganizationsService } from './organizations.service';

describe('OrganizationsService.purge', () => {
  const createService = (overrides?: {
    organization?: Record<string, unknown>;
    studentCount?: number;
    occupancyCount?: number;
    lessorCount?: number;
    lesseeCount?: number;
  }) => {
    const organization = {
      id: 1,
      name: '合作机构',
      status: 'archived',
      isHost: false,
      ...overrides?.organization,
    };
    const repo = {
      findOne: jest.fn().mockResolvedValue(organization),
      delete: jest.fn().mockResolvedValue({ affected: 1 }),
    };
    const studentRepo = { count: jest.fn().mockResolvedValue(overrides?.studentCount ?? 0) };
    const occupancyRepo = { count: jest.fn().mockResolvedValue(overrides?.occupancyCount ?? 0) };
    const rentalRepo = {
      count: jest.fn().mockResolvedValue(overrides?.lessorCount ?? 0),
    };
    rentalRepo.count.mockResolvedValueOnce(overrides?.lessorCount ?? 0);
    rentalRepo.count.mockResolvedValueOnce(overrides?.lesseeCount ?? 0);
    const service = new OrganizationsService(
      repo as never,
      studentRepo as never,
      occupancyRepo as never,
      rentalRepo as never,
    );
    return { service, repo, studentRepo, occupancyRepo, rentalRepo };
  };

  it('rejects organizations that are not archived or are the host', async () => {
    const notArchived = createService({ organization: { status: 'active' } });
    await expect(notArchived.service.purge(1)).rejects.toThrow(
      new BadRequestException('仅已归档机构可以永久删除，请先归档'),
    );

    const host = createService({ organization: { isHost: true } });
    await expect(host.service.purge(1)).rejects.toThrow(
      new BadRequestException('本机构不能永久删除'),
    );
    expect(notArchived.repo.delete).not.toHaveBeenCalled();
    expect(host.repo.delete).not.toHaveBeenCalled();
  });

  it('rejects organizations with student, occupancy, or rental references', async () => {
    const withStudents = createService({ studentCount: 1 });
    await expect(withStudents.service.purge(1)).rejects.toThrow(
      new BadRequestException('该机构存在关联数据（学生归属），无法永久删除'),
    );

    const withOccupancy = createService({ occupancyCount: 1 });
    await expect(withOccupancy.service.purge(1)).rejects.toThrow(
      new BadRequestException('该机构存在关联数据（入住责任机构），无法永久删除'),
    );

    const withLessee = createService({ lesseeCount: 1 });
    await expect(withLessee.service.purge(1)).rejects.toThrow(
      new BadRequestException('该机构存在关联数据（承租租赁订单），无法永久删除'),
    );
    expect(withLessee.repo.delete).not.toHaveBeenCalled();
  });

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