import { existsSync, renameSync, writeFileSync } from 'fs';
import { join } from 'path';
/**
 * Register the user's personal "My Folder" folder and grant them admin
 * folder_access. Idempotent — safe to call repeatedly and on existing
 * workspaces where the folder was provisioned before this helper existed
 * (repairs the missing folder_access row).
 *
 * Consolidated from four earlier call sites that each did half the work:
 * setup endpoint, /api/auth/users POST, server startup sweep, and
 * `studiograph user add` CLI. Skipping the grant left the user's own
 * personal folder invisible in the sidebar because `getAccessibleRepos()`
 * filters by folder_access.
 */
export async function ensurePersonalFolder(workspace, authService, user) {
    const folderName = `entries-${user.id}`;
    const config = await workspace.loadConfig();
    const alreadyRegistered = config.repos.some(r => r.name === folderName);
    if (!alreadyRegistered) {
        await workspace.registerRepo({
            name: folderName,
            display_name: 'My Folder',
            description: `Personal entries for ${user.displayName}`,
            personal: true,
            owner_id: user.id,
        });
    }
    const hasAccess = authService.getUserFolders(user.id).includes(folderName);
    if (!hasAccess) {
        authService.grantFolderAccess(user.id, folderName, 'admin');
    }
}
/**
 * Convert a departed user's personal folder into a normal (non-personal)
 * archive folder owned by the actor who deleted them. Matches Google
 * Drive's inherit-on-delete model: the content survives, the owner is
 * reassigned, and the "personal" semantics fall away so the folder
 * doesn't clash with the one-personal-folder-per-user invariant.
 *
 * Mutations applied (in order, best-effort non-atomic):
 *  1. Pick a collision-free new name: `archive-{slug}-{YYYY-MM-DD}`,
 *     escalating to `-2`, `-3`, … if needed.
 *  2. Rename the folder directory on disk.
 *  3. Update workspace.json: new name/path, display_name, clear the
 *     personal/owner_id flags, and write the new `.studiograph` marker.
 *  4. Update folder_access rows to the new name so the actor's inherited
 *     admin row keeps working.
 *  5. Push the updated workspace.json to the config remote (non-fatal).
 *
 * Returns the new folder name and display name so the caller can report
 * them to the UI. The caller should `workspaceManager.reloadConfig()`
 * after this completes to surface the change to in-memory graph state.
 */
export async function archivePersonalFolder(workspace, oldName, targetDisplayName, authService) {
    const config = await workspace.loadConfig();
    const repo = config.repos.find(r => r.name === oldName);
    if (!repo) {
        throw new Error(`Cannot archive '${oldName}' — folder not found in workspace config`);
    }
    if (!repo.personal) {
        throw new Error(`Cannot archive '${oldName}' — not a personal folder`);
    }
    const slug = slugify(targetDisplayName);
    const date = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
    const baseName = `archive-${slug}-${date}`;
    let newName = baseName;
    let suffix = 2;
    while (config.repos.some(r => r.name === newName)) {
        newName = `${baseName}-${suffix}`;
        suffix += 1;
    }
    const wsPath = workspace.workspacePath;
    const oldPath = join(wsPath, repo.path);
    const newPath = join(wsPath, newName);
    if (existsSync(oldPath)) {
        renameSync(oldPath, newPath);
    }
    repo.name = newName;
    repo.path = newName;
    repo.display_name = `Archive: ${targetDisplayName} (${date})`;
    delete repo.personal;
    delete repo.owner_id;
    const markerPath = join(newPath, '.studiograph');
    if (existsSync(markerPath)) {
        writeFileSync(markerPath, JSON.stringify({ repo_name: newName }, null, 2), 'utf-8');
    }
    workspace.writeConfig(config);
    authService.renameFolder(oldName, newName);
    workspace.pushWorkspaceConfig(`Archive personal folder on user delete: ${oldName} → ${newName}`);
    return { newName, newDisplayName: repo.display_name };
}
function slugify(name) {
    const cleaned = name
        .normalize('NFKD')
        .replace(/[̀-ͯ]/g, '') // strip combining diacritics
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '');
    return cleaned || 'user';
}
//# sourceMappingURL=personal-folder.js.map