import axios from 'axios';
import { DingtalkYidaService } from '../../../../src/modules/organization/dingtalk/sdk/dingtalk-yida.service';
import { DingtalkHrmService } from '../../../../src/modules/organization/dingtalk/sdk/dingtalk-hrm.service';

jest.mock('axios');

const mockedAxios = axios as jest.Mocked<typeof axios>;

describe('Dingtalk SDK services', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  describe('DingtalkYidaService', () => {
    const authService = {
      getNewApiHeaders: jest.fn().mockResolvedValue({ 'x-acs-dingtalk-access-token': 'token' }),
      appType: 'APP_TEST',
      systemToken: 'SYS_TOKEN',
      operatorId: 'manager001',
    };

    const service = new DingtalkYidaService(authService as any);

    it('应该使用高级查询二代接口查询宜搭表单', async () => {
      mockedAxios.post.mockResolvedValueOnce({
        data: { totalCount: 1, data: [{ formInstanceId: 'INS_1' }] },
      } as any);

      const result = await service.searchForm('FORM_1', '[]');

      expect(result).toEqual([{ formInstanceId: 'INS_1' }]);
      expect(mockedAxios.post).toHaveBeenCalledWith(
        'https://api.dingtalk.com/v1.0/yida/forms/instances/advances/queryAll',
        expect.objectContaining({
          formUuid: 'FORM_1',
          appType: 'APP_TEST',
          systemToken: 'SYS_TOKEN',
          userId: 'manager001',
          pageNumber: 1,
          pageSize: 100,
        }),
        { headers: { 'x-acs-dingtalk-access-token': 'token' } },
      );
    });

    it('应该使用 POST 调用 insertOrUpdate 接口', async () => {
      mockedAxios.post.mockResolvedValueOnce({ data: { success: true } } as any);

      const result = await service.createOrUpdateForm('FORM_2', '[{}]', '{"x":1}');

      expect(result).toEqual({ success: true });
      expect(mockedAxios.post).toHaveBeenCalledWith(
        'https://api.dingtalk.com/v1.0/yida/forms/instances/insertOrUpdate',
        expect.objectContaining({
          formUuid: 'FORM_2',
          searchCondition: '[{}]',
          formDataJson: '{"x":1}',
        }),
        { headers: { 'x-acs-dingtalk-access-token': 'token' } },
      );
      expect(mockedAxios.put).not.toHaveBeenCalled();
    });
  });

  describe('DingtalkHrmService', () => {
    it('四级部门映射应保留四级部门名称', async () => {
      const authService = { getAccessToken: jest.fn().mockResolvedValue('token') };
      const service = new DingtalkHrmService(authService as any);

      jest.spyOn(service, 'getDepartmentList')
        .mockResolvedValueOnce([{ dept_id: 10, name: '一级部门' }] as any)
        .mockResolvedValueOnce([{ dept_id: 20, name: '二级部门' }] as any)
        .mockResolvedValueOnce([{ dept_id: 30, name: '三级部门' }] as any)
        .mockResolvedValueOnce([{ dept_id: 40, name: '四级部门' }] as any);

      const result = await service.getDepartmentParents();

      expect(result[40]).toEqual({
        name: '四级部门',
        firstLevel: '一级部门',
      });
    });
  });
});
