import { ImportsController } from './imports.controller';

describe('ImportsController', () => {
  const principalRequest = {
    user: { id: 7, username: 'admin', permissions: [], isSuperAdmin: true },
    headers: { 'user-agent': 'jest-agent' },
    connection: { remoteAddress: '127.0.0.1' },
  };

  it('提交导入阶段成功后写入操作日志', async () => {
    const commitStep = jest.fn().mockResolvedValue({
      runId: 'run-1',
      stepKey: 'students',
      status: 'committed',
      created: 2,
      updated: 0,
      skipped: 0,
      failed: 0,
      total: 2,
      nextStepKey: null,
      runStatus: 'committed',
      message: '阶段「学生档案」提交完成：新建 2、更新 0、跳过 0、失败 0；全部阶段已完成',
    });
    const opLog = { log: jest.fn().mockResolvedValue(undefined) };
    const controller = new ImportsController({ commitStep } as never, opLog as never);

    await controller.commit(
      principalRequest as never,
      'run-1',
      'students',
      { decisions: [] },
    );

    expect(opLog.log).toHaveBeenCalledWith(
      expect.objectContaining({
        userId: 7,
        username: 'admin',
        module: '批量导入',
        action: '提交导入阶段',
        detail: expect.stringContaining('提交完成'),
        targetType: 'import_run',
        ipAddress: '127.0.0.1',
        userAgent: 'jest-agent',
      }),
    );
  });

  it('非 committed 回执（conflict/already_committed）不重复写日志', async () => {
    const commitStep = jest.fn().mockResolvedValue({
      runId: 'run-1',
      stepKey: 'students',
      status: 'conflict',
      created: 0,
      updated: 0,
      skipped: 0,
      failed: 0,
      total: 0,
      nextStepKey: null,
      runStatus: 'ready',
      message: '请先完成前置阶段',
    });
    const opLog = { log: jest.fn().mockResolvedValue(undefined) };
    const controller = new ImportsController({ commitStep } as never, opLog as never);

    await controller.commit(
      principalRequest as never,
      'run-1',
      'transfers',
      { decisions: [] },
    );

    expect(opLog.log).not.toHaveBeenCalled();
  });
});
