/** KV 中站点与分类的读写封装 */

export interface SiteRecord {
  id: string;
  name: string;
  url: string;
  description?: string;
  category?: string;
  tags?: string[];
  clicks?: number;
}

const KEY_SITES = 'sites';
const KEY_CATEGORIES = 'categories';

export async function getSites(kv: KVNamespace): Promise<SiteRecord[]> {
  const sitesData = (await kv.get(KEY_SITES, { type: 'json' })) as SiteRecord[] | null;
  return sitesData ?? [];
}

export async function putSites(kv: KVNamespace, sites: SiteRecord[]): Promise<void> {
  await kv.put(KEY_SITES, JSON.stringify(sites));
}

export async function getCategories(kv: KVNamespace): Promise<string[]> {
  const c = (await kv.get(KEY_CATEGORIES, { type: 'json' })) as string[] | null;
  return c ?? [];
}

export async function putCategories(kv: KVNamespace, categories: string[]): Promise<void> {
  await kv.put(KEY_CATEGORIES, JSON.stringify(categories));
}
