import { BadRequestException } from '@nestjs/common';
import { DepositsService } from './deposits.service';

describe('DepositsService.purge', () => {
  const createService = (overrides?: { deposit?: Record<string, unknown> }) => {
    const deposit = {
      id: 1,
      studentId: 2,
      amount: 500,
      status: 'archived',
      refundAmount: null,
      deductionAmount: 0,
      ...overrides?.deposit,
    };
    const repo = {
      findOne: jest.fn().mockResolvedValue(deposit),
      delete: jest.fn().mockResolvedValue({ affected: 1 }),
    };
    const installmentRepo = { count: jest.fn().mockResolvedValue(0) };
    const service = new DepositsService(
      repo as never,
      installmentRepo as never,
      {} as never,
    );
    return { service, repo, installmentRepo };
  };

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

  it('rejects deposits with refund or deduction amounts', async () => {
    const withRefund = createService({ deposit: { refundAmount: 100 } });
    await expect(withRefund.service.purge(1)).rejects.toThrow(
      new BadRequestException('该押金已有退款金额，无法永久删除'),
    );

    const withDeduction = createService({ deposit: { deductionAmount: 50 } });
    await expect(withDeduction.service.purge(1)).rejects.toThrow(
      new BadRequestException('该押金已有抵扣金额，无法永久删除'),
    );
    expect(withDeduction.repo.delete).not.toHaveBeenCalled();
  });

  it('rejects deposits with paid installments', async () => {
    const { service, installmentRepo, repo } = createService();
    installmentRepo.count.mockResolvedValue(1);
    await expect(service.purge(1)).rejects.toThrow(
      new BadRequestException('该押金存在已支付分期，无法永久删除'),
    );
    expect(repo.delete).not.toHaveBeenCalled();
  });

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