import axios from 'axios';
import { DingtalkAttendanceService } from '../../../../src/modules/organization/dingtalk/sdk/dingtalk-attendance.service';

jest.mock('axios');

describe('DingtalkAttendanceService', () => {
  const mockedAxios = axios as jest.Mocked<typeof axios>;

  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('批量查询假期余额失败时应自动回退为单人查询', async () => {
    const authService = {
      getAccessToken: jest.fn().mockResolvedValue('token'),
      operatorId: 'manager001',
    };

    mockedAxios.post
      .mockResolvedValueOnce({
        data: {
          errcode: 41,
          errmsg: 'Invalid arguments:userids',
          result: { leave_quotas: [], has_more: false },
        },
      } as any)
      .mockResolvedValueOnce({
        data: {
          errcode: 0,
          errmsg: 'ok',
          result: {
            leave_quotas: [
              { userid: 'user001', quota_num_per_day: 1000, used_num_per_day: 200 },
            ],
            has_more: false,
          },
        },
      } as any)
      .mockResolvedValueOnce({
        data: {
          errcode: 0,
          errmsg: 'ok',
          result: {
            leave_quotas: [
              { userid: 'user002', quota_num_per_day: 800, used_num_per_day: 100 },
            ],
            has_more: false,
          },
        },
      } as any);

    const service = new DingtalkAttendanceService(authService as any);
    const result = await service.searchLeaveQuota('leave-code', ['user001', 'user002']);

    expect(result).toHaveLength(2);
    expect(mockedAxios.post).toHaveBeenNthCalledWith(
      1,
      'https://oapi.dingtalk.com/topapi/attendance/vacation/quota/list',
      expect.objectContaining({
        userids: 'user001,user002',
        leave_code: 'leave-code',
      }),
      expect.any(Object),
    );
    expect(mockedAxios.post).toHaveBeenNthCalledWith(
      2,
      'https://oapi.dingtalk.com/topapi/attendance/vacation/quota/list',
      expect.objectContaining({
        userids: 'user001',
      }),
      expect.any(Object),
    );
    expect(mockedAxios.post).toHaveBeenNthCalledWith(
      3,
      'https://oapi.dingtalk.com/topapi/attendance/vacation/quota/list',
      expect.objectContaining({
        userids: 'user002',
      }),
      expect.any(Object),
    );
  });

  it('假期余额接口返回空 result 时应视为 0 条而不是抛错', async () => {
    const authService = {
      getAccessToken: jest.fn().mockResolvedValue('token'),
      operatorId: 'manager001',
    };

    mockedAxios.post.mockResolvedValueOnce({
      data: {
        errcode: 0,
        errmsg: 'ok',
      },
    } as any);

    const service = new DingtalkAttendanceService(authService as any);
    const result = await service.searchLeaveQuota('leave-code', ['user001']);

    expect(result).toEqual([]);
  });
});
