import { describe, it, expect, beforeEach, vi } from 'vitest';
import chrome from 'sinon-chrome';
import { setCacheEntriesBatch } from './cache-store.js';

describe('cache-store', () => {
  beforeEach(() => {
    chrome.flush();
    chrome.storage.local.get.resolves({});
    chrome.storage.local.set.resolves();
  });

  describe('setCacheEntriesBatch', () => {
    it('应在消息中包含 source 字段', async () => {
      const entries = [
        {
          source: 'xiaoyuzhou',
          sourceRef: 'podcast1',
          data: { title: 'Test Podcast' },
          meta: {},
        },
      ];

      await setCacheEntriesBatch('podcast', entries, {
        source: 'user-action',
      });

      // 验证发送消息
      expect(chrome.runtime.sendMessage.calledOnce).toBe(true);
      const message = chrome.runtime.sendMessage.getCall(0).args[0];

      expect(message).toEqual({
        type: 'xyz.cache.entityUpdated',
        entity: 'podcast',
        size: expect.any(Number),
        updated: expect.any(Number),
        source: 'user-action',
      });
    });

    it('source 默认值应为 background', async () => {
      const entries = [
        {
          source: 'xiaoyuzhou',
          sourceRef: 'podcast1',
          data: { title: 'Test Podcast' },
          meta: {},
        },
      ];

      await setCacheEntriesBatch('podcast', entries);

      const message = chrome.runtime.sendMessage.getCall(0).args[0];
      expect(message.source).toBe('background');
    });
  });
});
