import { beforeEach, describe, expect, it } from 'vitest';
import {
  cacheDingTalkDraft,
  cacheDingTalkServerSnapshot,
  commitDingTalkConfig,
  readDingTalkConfigCache,
  resetDingTalkConfigCache,
} from './integration-config-cache';

describe('DingTalk integration config page cache', () => {
  beforeEach(resetDingTalkConfigCache);

  it('keeps an unsaved secret when a background refresh returns', () => {
    cacheDingTalkDraft({ corpId: 'draft-corp', agentId: 'draft-key', appSecret: 'draft-secret' });
    cacheDingTalkServerSnapshot({ corpId: 'saved-corp', agentId: 'saved-key' }, true);

    expect(readDingTalkConfigCache()).toMatchObject({
      loaded: true,
      dirty: true,
      config: { corpId: 'saved-corp', agentId: 'saved-key' },
      formValues: {
        corpId: 'draft-corp',
        agentId: 'draft-key',
        appSecret: 'draft-secret',
      },
    });
  });

  it('clears the secret after a successful save', () => {
    cacheDingTalkDraft({ corpId: 'corp', agentId: 'key', appSecret: 'secret' });
    commitDingTalkConfig({ corpId: 'corp', agentId: 'key' });

    expect(readDingTalkConfigCache()).toMatchObject({
      loaded: true,
      dirty: false,
      formValues: { corpId: 'corp', agentId: 'key', appSecret: undefined },
    });
  });
});
