import { DingTalkService } from './dingtalk.service';

describe('DingTalkService attendance group deletion', () => {
  const originalAppKey = process.env.DINGTALK_APP_KEY;
  const originalAppSecret = process.env.DINGTALK_APP_SECRET;
  let service: DingTalkService;

  beforeEach(() => {
    process.env.DINGTALK_APP_KEY = 'test-app-key';
    process.env.DINGTALK_APP_SECRET = 'test-app-secret';
    service = new DingTalkService({} as never, {} as never);
    Object.assign(service, {
      accessToken: 'test-token',
      accessTokenCredentialKey: 'test-app-key:test-app-secret',
      tokenExpiresAt: Date.now() + 3_600_000,
    });
  });

  afterEach(() => {
    jest.restoreAllMocks();
    global.fetch = undefined as unknown as typeof fetch;
  });

  afterAll(() => {
    if (originalAppKey === undefined) delete process.env.DINGTALK_APP_KEY;
    else process.env.DINGTALK_APP_KEY = originalAppKey;
    if (originalAppSecret === undefined) delete process.env.DINGTALK_APP_SECRET;
    else process.env.DINGTALK_APP_SECRET = originalAppSecret;
  });

  it('converts groupId to groupKey before deleting the group', async () => {
    global.fetch = jest
      .fn()
      .mockResolvedValueOnce({
        json: jest.fn().mockResolvedValue({ errcode: 0, errmsg: 'ok', result: 'group-key-1' }),
      })
      .mockResolvedValueOnce({
        json: jest.fn().mockResolvedValue({ errcode: 0, errmsg: 'ok', success: true }),
      }) as jest.MockedFunction<typeof fetch>;

    await service.deleteAttendanceGroup(123, 'manager');

    expect(global.fetch).toHaveBeenNthCalledWith(
      1,
      expect.stringContaining('/topapi/attendance/groups/idtokey'),
      expect.objectContaining({ body: JSON.stringify({ op_user_id: 'manager', group_id: 123 }) }),
    );
    expect(global.fetch).toHaveBeenNthCalledWith(
      2,
      expect.stringContaining('/topapi/attendance/group/delete'),
      expect.objectContaining({ body: JSON.stringify({ op_userid: 'manager', group_key: 'group-key-1' }) }),
    );
  });
});
