/**
 * Tenant credential store.
 * Reads from /workspace/credentials.json (mounted read-only from host).
 * Writes go via IPC tasks (host daemon writes the file).
 */
import path from "path";
import { readJsonFile, writeIpcFile } from "../ipc.js";
import { getContext } from "../client.js";

export interface Credential {
  name: string;
  value: string;
  description?: string;
}

function credentialsPath(workspaceDir: string): string {
  return path.join(workspaceDir, "credentials.json");
}

function tasksDir(ipcDir: string): string {
  return path.join(ipcDir, "tasks");
}

function groupFolder(): string {
  return process.env.NANOCLAW_GROUP_FOLDER ?? "";
}

export async function listCredentials(workspaceDir = "/workspace/shared"): Promise<Credential[]> {
  const data = readJsonFile<Credential[]>(credentialsPath(workspaceDir));
  return data ?? [];
}

export async function getCredential(name: string, workspaceDir = "/workspace/shared"): Promise<Credential> {
  const creds = await listCredentials(workspaceDir);
  const cred = creds.find((c) => c.name === name);
  if (!cred) throw new Error(`Credential not found: ${name}`);
  return cred;
}

export async function setCredential(
  name: string,
  value: string,
  opts?: { description?: string },
  ipcDir?: string,
): Promise<void> {
  const dir = ipcDir ?? getContext().ipcDir;
  writeIpcFile(tasksDir(dir), {
    type: "creds_set",
    name,
    value,
    description: opts?.description,
    groupFolder: groupFolder(),
  });
}

export async function removeCredential(name: string, ipcDir?: string): Promise<void> {
  const dir = ipcDir ?? getContext().ipcDir;
  writeIpcFile(tasksDir(dir), {
    type: "creds_remove",
    name,
    groupFolder: groupFolder(),
  });
}
