import type { DingTalkConfigFormValues } from './integration-config-form';

export interface DingTalkSavedConfig {
  agentId: string;
  corpId: string;
}

interface DingTalkConfigCache {
  loaded: boolean;
  config: DingTalkSavedConfig | null;
  verified: boolean | null;
  formValues: Partial<DingTalkConfigFormValues>;
  dirty: boolean;
}

const cache: DingTalkConfigCache = {
  loaded: false,
  config: null,
  verified: null,
  formValues: {},
  dirty: false,
};

export function readDingTalkConfigCache(): DingTalkConfigCache {
  return {
    ...cache,
    config: cache.config ? { ...cache.config } : null,
    formValues: { ...cache.formValues },
  };
}

export function cacheDingTalkDraft(values: Partial<DingTalkConfigFormValues>): void {
  cache.formValues = { ...values };
  cache.dirty = true;
}

export function cacheDingTalkServerSnapshot(
  config: DingTalkSavedConfig | null,
  verified: boolean | null,
): void {
  cache.loaded = true;
  cache.config = config ? { ...config } : null;
  cache.verified = verified;
  if (!cache.dirty) {
    cache.formValues = config ? { ...config, appSecret: undefined } : {};
  }
}

export function commitDingTalkConfig(config: DingTalkSavedConfig): void {
  cache.loaded = true;
  cache.config = { ...config };
  cache.formValues = { ...config, appSecret: undefined };
  cache.dirty = false;
}

export function resetDingTalkConfigCache(): void {
  cache.loaded = false;
  cache.config = null;
  cache.verified = null;
  cache.formValues = {};
  cache.dirty = false;
}
