import {
  getSenderDetails,
  getDomainProperties,
  uploadFile,
  getCdnTransformationConfig,
  createWhatsappTemplate,
  getMetaTags,
  getSupportVideosConfig,
  getNavigationConfigApi,
  getAllTemplates,
  getTemplateDetails,
  getTemplateInfoById,
  askAiraForLiquid,
  getLiquidTags,
  fetchSchemaForEntity,
  getDefaultBeeTemplates,
  getEdmTemplates,
  searchCustomers,
  extractTagsWithMetaData,
  updateEmailPreview,
  sendTestMessage,
  fetchTestCustomers,
  fetchTestGroups,
  getBulkCustomerDetails,
  createTestMessageMeta,
  updateTestMessageMeta,
  updateMetaConfig,
  getMediaDetails,
  getAssetStatus,
  getBeePopupBuilderToken,
  getCmsAccounts,
  getMembersLookup,
  createTestCustomer,
} from '../api';
import { mockData } from './mockData';
import getSchema from '../getSchema';
const sampleFile = require('../../assets/line.png');

let mockDecompressJsonObject;
let mockAddBaseToTemplate;
jest.mock('@capillarytech/cap-ui-utils', () => {
  mockDecompressJsonObject = jest.fn();
  mockAddBaseToTemplate = jest.fn();
  return {
    ...jest.requireActual('@capillarytech/cap-ui-utils'),
    decompressJsonObject: mockDecompressJsonObject,
    addBaseToTemplate: mockAddBaseToTemplate,
  };
});

jest.mock('../getSchema', () => jest.fn());

describe('getSenderDetails -- Test with valid responses', () => {
  it('Should return correct response', () =>
    expect(getSenderDetails('WHATSAPP', -1)).toEqual(Promise.resolve()));
});

describe('getDomainProperties -- Test with valid responses', () => {
  it('Should return correct response', () => {
    expect(getDomainProperties(['SMS', 'EMAIL'], null)).toEqual(Promise.resolve());
  });
});

describe('getCdnTransformationConfigs -- Test with valid responses', () => {
  it('Should return correct response', () =>
    expect(getCdnTransformationConfig()).toEqual(Promise.resolve()));
});

describe('uploadFile -- whatsapp image upload', () => {
  it('Should return correct response', () =>
    expect(
      uploadFile({
        file: new Image(),
        assetType: 'image',
        fileParams: {
          width: 275,
          height: 183,
          error: false,
        },
        whatsappParams: {
          source: 'whatsapp',
          wabaId: '107499611940863',
          accessToken: 'Bearer gDwEuRIm9icV6phixociSw==',
          hostName: 'karixwhatsappbulk',
          baseUrl: 'https://api.whatsapp.com/v1',
        },
      }),
    ).toEqual(Promise.resolve()));

  it('Uploads the file with the original filename when encodeURIComponent fails', async () => {
    // Mocking the encodeURIComponent function to throw an error
    global.encodeURIComponent = jest.fn(() => { throw new Error('encodeURIComponent error'); });
    const blob = new Blob([''], { type: 'image/jpeg' });
    const file = new File([blob], '@%test.jpeg', { type: 'image/jpeg' });
    expect(
        uploadFile({
          file,
          assetType: 'image',
          fileParams: {
            width: 275,
            height: 183,
            error: false,
          },
          whatsappParams: {},
        }),
      ).toEqual(Promise.resolve());
  });
});

describe('createWhatsappTemplate -- Test with valid responses', () => {
  it('Should return correct response', () =>
    expect(
      createWhatsappTemplate({gupshupMediaFile: [sampleFile], payload: mockData.createWhatsappPayload}),
    ).toEqual(Promise.resolve()));
  it('Should return correct response when single file is present', () =>
    expect(
      createWhatsappTemplate({gupshupMediaFile: sampleFile, payload: mockData.createWhatsappPayload}),
    ).toEqual(Promise.resolve()));
});

describe('getMetaTags -- Test with valid responses', () => {
  it('Should return correct response', () =>
    expect(
      getMetaTags({previewUrl: 'https://capillarytech.com'}),
    ).toEqual(Promise.resolve()));
});

describe('getSupportVideosConfig -- Test with valid responses', () => {
  it('Should return correct response', () =>
    expect(getSupportVideosConfig()).toEqual(Promise.resolve()));
});

describe('getNavigationConfigApi -- Test with valid responses', () => {
  it('Should return correct response', () =>
    expect(getNavigationConfigApi()).toEqual(Promise.resolve()));
});

describe('getAllTemplates -- Test with valid responses', () => {
  beforeEach(() => {
    global.fetch = jest.fn(); // Mocking global fetch function
  });

  afterEach(() => {
    jest.restoreAllMocks(); // Restore all mocks after each test
  });

  it('Should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: {
          _id: '123',
        },
      }),
    }));
    mockDecompressJsonObject.mockReturnValue({
      _id: '123',
    });
    expect(await getAllTemplates({channel: 'email'})).toEqual({
      response: {
        _id: '123',
      },
      status: 200,
    });
  });

  it('Should work for empty response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({json: () => Promise.resolve(),}));
    mockDecompressJsonObject.mockReturnValue();
    expect(await getAllTemplates({channel: 'email'})).toEqual({
      response: undefined,
    });
  });

  it('Should not return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        data: {
          _id: '123',
        },
      }),
    }));
    mockDecompressJsonObject.mockReturnValue({
      _id: '123',
    });
    expect(await getAllTemplates({channel: 'email'})).toEqual({
      data: {
        _id: '123',
      },
      response: {
        _id: '123',
      },
      status: 200,
    });
  });
});

describe('getTemplateDetails -- Test with valid responses', () => {
  beforeEach(() => {
    global.fetch = jest.fn(); // Mocking global fetch function
  });

  afterEach(() => {
    jest.restoreAllMocks(); // Restore all mocks after each test
  });
  it('Should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: {
          _id: '123',
          versions: {
            history: ['v1', 'v2'],
          },
        },
      }),
    }));
    mockDecompressJsonObject.mockReturnValue({
      _id: '123',
      versions: {
        history: ['v1', 'v2'],
      },
    });
    expect(await getTemplateDetails({id: '123', channel: 'email'})).toEqual({
      response: {
        _id: '123',
        versions: {
          history: ['v1', 'v2'],
          base: {
            "0":"v","1":"1","subject":undefined,
          },
        },
      },
      status: 200,
    });
  });
  it('Should work incase of empty response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
      }),
    }));
    mockDecompressJsonObject.mockReturnValue();
    expect(await getTemplateDetails({id: '123', channel: 'email'})).toEqual({
      status: 200,
    });
  });
  it('Should return response when channel is not email', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        data: {
          _id: '123',
          versions: {
            history: ['v1', 'v2'],
          },
        },
      }),
    }));
    mockDecompressJsonObject.mockReturnValue({
      _id: '123',
      versions: {
        history: ['v1', 'v2'],
      },
    });
    expect(await getTemplateDetails({id: '123'})).toEqual({
      data: {
        _id: '123',
        versions: {
          history: ['v1', 'v2'],
        },
      },
      response: {
        _id: '123',
        versions: {
          history: ['v1', 'v2'],
        },
      },
      status: 200,
    });
  });
});

describe('getTemplateInfoById -- Test with valid responses', () => {
  beforeEach(() => {
    global.fetch = jest.fn(); // Mocking global fetch function
  });

  afterEach(() => {
    jest.restoreAllMocks(); // Restore all mocks after each test
  });
  it('Should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: {
          _id: '123',
        },
      }),
    }));
    mockDecompressJsonObject.mockReturnValue({
      _id: '123',
    });
    expect(await getTemplateInfoById({id: '123', username: 'capillary_zns', 'oa_id': 'jfhagsdhj', token: 'tuyagjahs'})).toEqual({
      response: {
        _id: '123',
      },
      status: 200,
    });
  });

  it('Should not return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        data: {
          _id: '1234',
        },
      }),
    }));
    mockDecompressJsonObject.mockReturnValue({
      _id: '1234',
    });
    expect(await getTemplateInfoById({id: '1234', username: 'capillary_zns', 'oa_id': 'jfhagsdhj', token: 'tuyagjahs'})).toEqual({
      data: {
        _id: '1234',
      },
      response: {
        _id: '1234',
      },
      status: 200,
    });
  });

  it('Should not return correct response when data is undefined', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve(),
    }));
    mockDecompressJsonObject.mockReturnValue(undefined);
    expect(await getTemplateInfoById({id: '123', username: 'capillary_zns', 'oa_id': 'jfhagsdhj', token: 'tuyagjahs'})).toEqual({
      response: undefined,
    });
  });
});

describe('askAiraForLiquid -- Test with various responses', () => {
  beforeEach(() => {
    global.fetch = jest.fn(); // Mocking global fetch function
  });

  afterEach(() => {
    jest.restoreAllMocks(); // Restore all mocks after each test
  });

  it('Should return correct response when syntax errors are present', async () => {
    global.fetch.mockReturnValue(
      Promise.resolve({
        status: 200,
        json: () =>
          Promise.resolve({
            status: 200,
            response: 'Error description here',
          }),
      })
    );

    const templateContent = 'Invalid Liquid Template';
    const errorMessage = 'Parser error message';
    const response = await askAiraForLiquid({ templateContent, errorMessage });

    expect(response).toEqual({
      status: 200,
      response: 'Error description here',
    });
  });

  it('Should return empty string when no syntax errors are present', async () => {
    global.fetch.mockReturnValue(
      Promise.resolve({
        status: 200,
        json: () =>
          Promise.resolve({
            status: 200,
            response: '',
          }),
      })
    );

    const templateContent = 'Valid Liquid Template';
    const errorMessage = '';
    const response = await askAiraForLiquid({ templateContent, errorMessage });

    expect(response).toEqual({
      status: 200,
      response: '',
    });
  });

  it('Should handle server errors gracefully', async () => {
    global.fetch.mockReturnValue(
      Promise.resolve({
        status: 500,
        json: () =>
          Promise.resolve({
            status: 500,
            error: 'Internal Server Error',
          }),
      })
    );

    const templateContent = 'Any Template';
    const errorMessage = 'Any Error Message';
    const response = await askAiraForLiquid({ templateContent, errorMessage });

    expect(response).toEqual({
      status: 500,
      error: 'Internal Server Error',
    });
  });
});

describe('getLiquidTags -- Test with various responses', () => {
  beforeEach(() => {
    global.fetch = jest.fn(); // Mocking global fetch function
  });

  afterEach(() => {
    jest.restoreAllMocks(); // Restore all mocks after each test
  });

  it('Should return correct tags when content has Liquid syntax', async () => {
    const mockResponse = {
      status: 200,
      json: () =>
        Promise.resolve({
          status: 200,
          response: ['tag1', 'tag2'],
        }),
    };
    global.fetch.mockReturnValue(Promise.resolve(mockResponse));

    const content = 'Some Liquid content with tags';
    const response = await getLiquidTags(content);

    expect(response).toEqual({
      status: 200,
      response: ['tag1', 'tag2'],
    });
  });

  it('Should return empty array when content has no Liquid tags', async () => {
    const mockResponse = {
      status: 200,
      json: () =>
        Promise.resolve({
          status: 200,
          response: [],
        }),
    };
    global.fetch.mockReturnValue(Promise.resolve(mockResponse));

    const content = 'Plain content without Liquid tags';
    const response = await getLiquidTags(content);

    expect(response).toEqual({
      status: 200,
      response: [],
    });
  });

  it('Should handle server errors gracefully', async () => {
    const mockResponse = {
      status: 500,
      json: () =>
        Promise.resolve({
          status: 500,
          error: 'Internal Server Error',
        }),
    };
    global.fetch.mockReturnValue(Promise.resolve(mockResponse));

    const content = 'Any content';
    const response = await getLiquidTags(content);

    expect(response).toEqual({
      status: 500,
      error: 'Internal Server Error',
    });
  });
});

describe('fetchSchemaForEntity', () => {
  it('should fetch schema for version v2 and type LAYOUT', async () => {
    const queryParams = { version: 'v2', type: 'LAYOUT', layout: 'testLayout' };
    const mockLayout = { id: 'layout1', name: 'Test Layout' };

    getSchema.mockReturnValue(Promise.resolve(mockLayout));

    const result = await fetchSchemaForEntity({ queryParams });

    expect(getSchema).toHaveBeenCalledWith(queryParams.layout);
    expect(result).toEqual(mockLayout);
  });

  it('should handle errors when fetching schema', async () => {
    const queryParams = { version: 'v2', type: 'LAYOUT', layout: 'testLayout' };
    const mockError = new Error('Failed to fetch schema');

    getSchema.mockReturnValue(Promise.reject(mockError));

    console.error = jest.fn();

    const result = await fetchSchemaForEntity({ queryParams });

    expect(getSchema).toHaveBeenCalledWith(queryParams.layout);
    expect(result).toBeUndefined();
    expect(console.error).toHaveBeenCalledWith(mockError);
  });
});

describe('Email Template APIs', () => {
  beforeEach(() => {
    global.fetch = jest.fn();
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  const sharedTests = (apiFunction, functionName) => {
    it('should handle successful response', async () => {
      const mockResponse = { response: 'compressed-data' };
      const mockDecompressed = { template: 'decompressed-data' };
      const mockWithBase = { template: 'data-with-base' };

      global.fetch.mockReturnValue(Promise.resolve({
        status: 200,
        json: () => Promise.resolve(mockResponse),
      }));
      mockDecompressJsonObject.mockReturnValue(mockDecompressed);
      mockAddBaseToTemplate.mockReturnValue(mockWithBase);

      const result = await apiFunction();
      expect(result).toEqual({
        ...mockResponse,
        response: mockDecompressed,
      });
    });

    it('should handle response property as empty object', async () => {
      const mockResponse = { response: {} };

      global.fetch.mockReturnValue(Promise.resolve({
        status: 200,
        json: () => Promise.resolve(mockResponse),
      }));
      mockDecompressJsonObject.mockReturnValue({});
      mockAddBaseToTemplate.mockReturnValue({});

      const result = await apiFunction();
      expect(result).toEqual({
        ...mockResponse,
        response: {},
      });
    });

    it('should handle missing response property', async () => {
      const mockResponse = {};

      global.fetch.mockReturnValue(Promise.resolve({
        status: 200,
        json: () => Promise.resolve(mockResponse),
      }));
      mockDecompressJsonObject.mockReturnValue('');
      mockAddBaseToTemplate.mockReturnValue('');

      const result = await apiFunction();
      expect(result).toEqual({
        response: '',
      });
    });

    it('should handle null response', async () => {
      global.fetch.mockReturnValue(Promise.resolve({
        json: () => Promise.resolve(null),
      }));
      mockDecompressJsonObject.mockReturnValue('');
      mockAddBaseToTemplate.mockReturnValue('');

      const result = await apiFunction();
      expect(result).toEqual({
        response: '',
      });
    });

    it('should handle undefined response', async () => {
      global.fetch.mockReturnValue(Promise.resolve({
        json: () => Promise.resolve(undefined),
      }));
      mockDecompressJsonObject.mockReturnValue('');
      mockAddBaseToTemplate.mockReturnValue('');

      const result = await apiFunction();
      expect(result).toEqual({
        response: '',
      });
    });

    it('should handle fetch failure', async () => {
      global.fetch.mockRejectedValue(new Error('Network error'));
      mockDecompressJsonObject.mockReturnValue(undefined);
      mockAddBaseToTemplate.mockReturnValue(undefined);
      console.error = jest.fn();

      const result = await apiFunction();

      expect(result).toEqual({
        response: undefined,
      });
    });
  };

  describe('getEdmTemplates', () => {
    sharedTests(getEdmTemplates, 'getEdmTemplates');
  });

  describe('getDefaultBeeTemplates', () => {
    sharedTests(getDefaultBeeTemplates, 'getDefaultBeeTemplates');
  });
});

describe('searchCustomers', () => {
  it('should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test',
      }),
    }));
    const result = await searchCustomers({ query: 'test' });
    expect(result).toEqual({
      status: 200,
      response: 'test',
    });
  });
  it('should handle fetch failure', async () => {
    global.fetch.mockRejectedValue({ error: 'Network error' });
    const result = await searchCustomers({ query: 'test' });
    expect(result).toEqual({
      error: 'Network error',
    });
  });
});
describe('extractTagsWithMetaData', () => {
  it('should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test',
      }),
    }));
    const result = await extractTagsWithMetaData({ query: 'test' });
    expect(result).toEqual({
      status: 200,
      response: 'test',
    });
  });
  it('should handle fetch failure', async () => {
    global.fetch.mockRejectedValue({ error: 'Network error' });
    const result = await extractTagsWithMetaData({ query: 'test' });
    expect(result).toEqual({
      error: 'Network error',
    });
  });
});

describe('updateEmailPreview', () => {
  it('should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test',
      }),
    }));
    const result = await updateEmailPreview({ query: 'test' });
    expect(result).toEqual({
      status: 200,
      response: 'test',
    });
  });
  it('should handle fetch failure', async () => {
    global.fetch.mockRejectedValue({ error: 'Network error' });
    const result = await updateEmailPreview({ query: 'test' });
    expect(result).toEqual({
      error: 'Network error',
    });
  });
});

describe('sendTestMessage', () => {
  it('should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test',
      }),
    }));
    const result = await sendTestMessage({ query: 'test' });
    expect(result).toEqual({
      status: 200,
      response: 'test',
    });
  });
});
describe('fetchTestCustomers', () => {
  it('should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test',
      }),
    }));
    const result = await fetchTestCustomers({ query: 'test' });
    expect(result).toEqual({
      status: 200,
      response: 'test',
    });
  });
  it('should handle fetch failure', async () => {
    global.fetch.mockRejectedValue({ error: 'Network error' });
    const result = await fetchTestCustomers({ query: 'test' });
    expect(result).toEqual({
      error: 'Network error',
    });
  });
});
describe('fetchTestGroups', () => {
  it('should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test',
      }),
    }));
    const result = await fetchTestGroups({ query: 'test' });
    expect(result).toEqual({
      status: 200,
      response: 'test',
    });
  });
});
describe('getBulkCustomerDetails', () => {
  it('should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test',
      }),
    }));
    const result = await getBulkCustomerDetails({ query: 'test' });
    expect(result).toEqual({
      status: 200,
      response: 'test',
    });
  });
  it('should handle fetch failure', async () => {
    global.fetch.mockRejectedValue({ error: 'Network error' });
    const result = await getBulkCustomerDetails({ query: 'test' });
    expect(result).toEqual({
      error: 'Network error',
    });
  });
});
describe('createTestMessageMeta', () => {
  it('should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test',
      }),
    }));
    const result = await createTestMessageMeta({ query: 'test' });
    expect(result).toEqual({
      status: 200,
      response: 'test',
    });
  });
});
describe('updateTestMessageMeta', () => {
  it('should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test',
      }),
    }));
    const result = await updateTestMessageMeta({ query: 'test' });
    expect(result).toEqual({
      status: 200,
      response: 'test',
    });
  });
});

describe('updateMetaConfig', () => {
  it('should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test',
      }),
    }));
    const result = await updateMetaConfig({ query: 'test' });
    expect(result).toEqual({
      status: 200,
      response: 'test',
    });
  });
});

describe('getMediaDetails', () => {
  it('should return correct response on success', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test media details',
      }),
    }));
    const result = await getMediaDetails({ id: 'testId' });
    expect(result).toEqual({
      status: 200,
      response: 'test media details',
    });
  });

  it('should handle fetch failure', async () => {
    global.fetch.mockRejectedValue({ error: 'Network error' });
    const result = await getMediaDetails({ id: 'testId' });
    expect(result).toEqual({
      error: 'Network error',
    });
  });
});

describe('getAssetStatus', () => {
  beforeEach(() => {
    global.fetch = jest.fn();
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  it('should return correct response on success', async () => {
    const mockResponse = {
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: {
          assetId: 'asset-123',
          status: 'completed',
          asset: {
            _id: 'asset-123',
            type: 'IMAGE',
            url: 'https://example.com/image.jpg',
          },
        },
      }),
    };
    global.fetch.mockReturnValue(Promise.resolve(mockResponse));
    
    const result = await getAssetStatus('image', 'asset-123');
    
    expect(result).toEqual({
      status: 200,
      response: {
        assetId: 'asset-123',
        status: 'completed',
        asset: {
          _id: 'asset-123',
          type: 'IMAGE',
          url: 'https://example.com/image.jpg',
        },
      },
    });
  });

  it('should handle processing status', async () => {
    const mockResponse = {
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: {
          assetId: 'asset-123',
          status: 'processing',
          message: 'Asset is being processed',
        },
      }),
    };
    global.fetch.mockReturnValue(Promise.resolve(mockResponse));
    
    const result = await getAssetStatus('video', 'asset-123');
    
    expect(result).toEqual({
      status: 200,
      response: {
        assetId: 'asset-123',
        status: 'processing',
        message: 'Asset is being processed',
      },
    });
  });

  it('should handle failed status', async () => {
    const mockResponse = {
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: {
          assetId: 'asset-123',
          status: 'failed',
          error: 'Processing failed',
        },
      }),
    };
    global.fetch.mockReturnValue(Promise.resolve(mockResponse));
    
    const result = await getAssetStatus('document', 'asset-123');
    
    expect(result).toEqual({
      status: 200,
      response: {
        assetId: 'asset-123',
        status: 'failed',
        error: 'Processing failed',
      },
    });
  });

  it('should handle fetch failure', async () => {
    global.fetch.mockRejectedValue({ error: 'Network error' });
    
    const result = await getAssetStatus('image', 'asset-123');
    
    expect(result).toEqual({
      error: 'Network error',
    });
  });

  it('should construct correct URL with type and assetId', async () => {
    const mockResponse = {
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: { assetId: 'asset-123', status: 'processing' },
      }),
    };
    global.fetch.mockReturnValue(Promise.resolve(mockResponse));
    
    await getAssetStatus('video', 'asset-456');
    
    expect(global.fetch).toHaveBeenCalled();
    const callArgs = global.fetch.mock.calls[0];
    expect(callArgs[0]).toContain('/assets/video/asset-456/status');
  });
});

describe('getBeePopupBuilderToken', () => {
  it('should return correct response', async () => {
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({
        status: 200,
        response: 'test',
      }),
    }));
    const result = await getBeePopupBuilderToken();
    expect(result).toEqual({
      status: 200,
      response: 'test',
    });
  });
});

describe('getCmsAccounts', () => {
  it('should return a promise (line 473-476)', () => {
    // Similar to other API tests, just verify it returns a Promise
    const result = getCmsAccounts('bee');
    expect(result).toBeInstanceOf(Promise);
  });

  it('should be callable with cmsType parameter', () => {
    // Verify function exists and can be called
    expect(typeof getCmsAccounts).toBe('function');
    const result = getCmsAccounts('bee');
    expect(result).toBeInstanceOf(Promise);
  });
});

describe('getMembersLookup', () => {
  beforeEach(() => {
    global.fetch = jest.fn();
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({ success: true, response: { exists: false, customerDetails: [] } }),
    }));
  });

  it('should return a Promise', () => {
    const result = getMembersLookup('email', 'user@example.com');
    expect(result).toBeInstanceOf(Promise);
  });

  it('should be callable with identifierType and identifierValue', () => {
    expect(typeof getMembersLookup).toBe('function');
    const result = getMembersLookup('mobile', '9123456789');
    expect(result).toBeInstanceOf(Promise);
  });

  it('should call fetch with correct URL encoding and GET method', () => {
    global.fetch.mockClear();
    getMembersLookup('email', 'user+test@example.com');
    expect(global.fetch).toHaveBeenCalled();
    const calls = global.fetch.mock.calls;
    const anyMembersCall = calls.find((c) => c[0] && String(c[0]).includes('members'));
    expect(anyMembersCall).toBeDefined();
    expect(anyMembersCall[0]).toContain('identifierType=');
    expect(anyMembersCall[0]).toContain('identifierValue=');
    expect(anyMembersCall[1]?.method || 'GET').toBe('GET');
  });
});

describe('createTestCustomer', () => {
  beforeEach(() => {
    global.fetch = jest.fn();
    global.fetch.mockReturnValue(Promise.resolve({
      status: 200,
      json: () => Promise.resolve({ success: true }),
    }));
  });

  it('should return a Promise', () => {
    const payload = { customer: { email: 'test@example.com', firstName: 'Test' } };
    const result = createTestCustomer(payload);
    expect(result).toBeInstanceOf(Promise);
  });

  it('should accept customerId payload for existing customer', () => {
    const payload = { customerId: 'cust-123' };
    const result = createTestCustomer(payload);
    expect(result).toBeInstanceOf(Promise);
    expect(global.fetch).toHaveBeenCalled();
    const lastCall = global.fetch.mock.calls[global.fetch.mock.calls.length - 1];
    expect(lastCall[0]).toContain('testCustomers');
    expect(lastCall[1].method).toBe('POST');
    expect(lastCall[1].body).toBe(JSON.stringify(payload));
  });

  it('should call fetch with /testCustomers URL and POST method', () => {
    const payload = { customer: { email: 'n@b.co', firstName: 'N' } };
    createTestCustomer(payload);
    expect(global.fetch).toHaveBeenCalled();
    const lastCall = global.fetch.mock.calls[global.fetch.mock.calls.length - 1];
    expect(lastCall[0]).toContain('testCustomers');
    expect(lastCall[1].method).toBe('POST');
    expect(lastCall[1].body).toBe(JSON.stringify(payload));
  });
});

import {
  archiveTemplate,
  unarchiveTemplate,
  bulkArchiveTemplates,
  bulkUnarchiveTemplates,
} from '../api';

describe('archiveTemplate', () => {
  beforeEach(() => {
    global.fetch = jest.fn().mockReturnValue(Promise.resolve({ json: () => Promise.resolve({}) }));
  });

  it('should call PUT on archive endpoint', () => {
    archiveTemplate({ channel: 'EMAIL', id: 'id123' });
    expect(global.fetch).toHaveBeenCalled();
    const lastCall = global.fetch.mock.calls[global.fetch.mock.calls.length - 1];
    expect(lastCall[1].method).toBe('PUT');
  });
});

describe('unarchiveTemplate', () => {
  beforeEach(() => {
    global.fetch = jest.fn().mockReturnValue(Promise.resolve({ json: () => Promise.resolve({}) }));
  });

  it('should call PUT on unarchive endpoint', () => {
    unarchiveTemplate({ channel: 'EMAIL', id: 'id123' });
    expect(global.fetch).toHaveBeenCalled();
    const lastCall = global.fetch.mock.calls[global.fetch.mock.calls.length - 1];
    expect(lastCall[1].method).toBe('PUT');
  });
});

describe('bulkArchiveTemplates', () => {
  beforeEach(() => {
    global.fetch = jest.fn().mockReturnValue(Promise.resolve({ json: () => Promise.resolve({}) }));
  });

  it('should call PUT on bulk archive endpoint with ids', () => {
    bulkArchiveTemplates({ channel: 'EMAIL', ids: ['id1', 'id2'] });
    expect(global.fetch).toHaveBeenCalled();
    const lastCall = global.fetch.mock.calls[global.fetch.mock.calls.length - 1];
    expect(lastCall[1].method).toBe('PUT');
  });
});

describe('bulkUnarchiveTemplates', () => {
  beforeEach(() => {
    global.fetch = jest.fn().mockReturnValue(Promise.resolve({ json: () => Promise.resolve({}) }));
  });

  it('should call PUT on bulk unarchive endpoint with ids', () => {
    bulkUnarchiveTemplates({ channel: 'EMAIL', ids: ['id1', 'id2'] });
    expect(global.fetch).toHaveBeenCalled();
    const lastCall = global.fetch.mock.calls[global.fetch.mock.calls.length - 1];
    expect(lastCall[1].method).toBe('PUT');
  });
});
