import { ref } from 'vue';

import type { FileGroupCachePayload, FileGroupOptionItem } from '#/api/core/file-group';
import { getFileGroupOptions } from '#/api/core/file-group';

const STORAGE_KEY = 'file-group-options-cache';

/**
 * 读取本地分组选项缓存
 */
function readLocalCache(): FileGroupCachePayload | null {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) {
      return null;
    }
    const parsed = JSON.parse(raw) as FileGroupCachePayload;
    if (!parsed || !Array.isArray(parsed.items)) {
      return null;
    }
    return parsed;
  } catch {
    return null;
  }
}

/**
 * 写入本地分组选项缓存（hash 与服务端 Redis 一致）
 */
function writeLocalCache(payload: FileGroupCachePayload) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));
}

/**
 * 文件分组选项缓存 composable
 * 右键菜单打开时调用 loadGroupOptions 获取最新列表
 */
export function useFileGroupCache() {
  const groupOptions = ref<FileGroupOptionItem[]>([]);
  const loading = ref(false);

  /**
   * 加载分组选项（hash 未变时 result=0，使用本地缓存）
   */
  async function loadGroupOptions(force = false): Promise<FileGroupOptionItem[]> {
    loading.value = true;
    try {
      const cached = readLocalCache();
      const hash = force ? undefined : cached?.hash;
      const res = (await getFileGroupOptions(hash)) as any;
      const result = res?.result ?? res?.data ?? res;
      const serverHash = res?.message ?? cached?.hash ?? '';

      if (result === 0 && cached?.items?.length) {
        groupOptions.value = cached.items;
        return cached.items;
      }

      const items = Array.isArray(result) ? result : [];
      writeLocalCache({ hash: serverHash, items });
      groupOptions.value = items;
      return items;
    } finally {
      loading.value = false;
    }
  }

  /** 分组 CRUD 后强制刷新缓存 */
  async function invalidateGroupOptions() {
    localStorage.removeItem(STORAGE_KEY);
    return loadGroupOptions(true);
  }

  return {
    groupOptions,
    loading,
    loadGroupOptions,
    invalidateGroupOptions,
  };
}
