// api.ts から分割（挙動不変）: ユーザー/スペースフォルダのファイル（browser-macros / recordings）。
import { BASE, buildQuery } from './client';

// --- User/space folder files (browser-macros / recordings) ---
export interface FolderFileEntry { name: string; size: number; mtime: string }

/**
 * List files in a writable user-folder subdir. Passing `spaceId` scopes the
 * listing to that space's folder (`data/spaces/{id}/{subdir}`); omitting it
 * targets the per-user folder. Matches the convention used by the piece/agents
 * space-scoped fetchers above.
 */
export async function listFolderFiles(subdir: 'browser-macros' | 'recordings', spaceId?: string): Promise<FolderFileEntry[]> {
  const r = await fetch(`${BASE}/users/me/folder/list${buildQuery({ subdir, spaceId })}`, { credentials: 'same-origin' });
  if (!r.ok) throw new Error(`listFolderFiles: ${r.status}`);
  return (await r.json() as { files: FolderFileEntry[] }).files;
}

/** Read one folder file's text content (space-scoped when `spaceId` is given). */
export async function getFolderFile(subdir: 'browser-macros' | 'recordings', path: string, spaceId?: string): Promise<string> {
  const r = await fetch(`${BASE}/users/me/folder/file${buildQuery({ subdir, path, spaceId })}`, { credentials: 'same-origin' });
  if (!r.ok) throw new Error(`getFolderFile: ${r.status}`);
  return r.text();
}

/** Delete one folder file (space-scoped when `spaceId` is given). */
export async function deleteFolderFile(subdir: 'browser-macros' | 'recordings', path: string, spaceId?: string): Promise<void> {
  const r = await fetch(`${BASE}/users/me/folder/file${buildQuery({ subdir, path, spaceId })}`, { method: 'DELETE', credentials: 'same-origin' });
  if (!r.ok) throw new Error(`deleteFolderFile: ${r.status}`);
}
