import * as vscode from "vscode";

/**
 * Encrypted credential store backed by VS Code's SecretStorage API.
 *
 * All server-specific secrets (tokens, API keys, PATs) are stored here
 * rather than in plain-text config files. The VS Code platform handles
 * encryption using the OS keychain (macOS Keychain, Windows Credential
 * Vault, or libsecret on Linux).
 *
 * Keys follow the pattern: `mcpGrid.<serverId>.<secretName>`
 * Users never see the storage location.
 */
export class SecretStore {
  constructor(private readonly _secrets: vscode.SecretStorage) {}

  /** Store a secret for a specific server. */
  async setServerSecret(
    serverId: string,
    secretName: string,
    value: string
  ): Promise<void> {
    const key = this._key(serverId, secretName);
    await this._secrets.store(key, value);
  }

  /** Retrieve a secret for a specific server. */
  async getServerSecret(
    serverId: string,
    secretName: string
  ): Promise<string | undefined> {
    const key = this._key(serverId, secretName);
    return this._secrets.get(key);
  }

  /** Delete a specific secret. */
  async deleteServerSecret(
    serverId: string,
    secretName: string
  ): Promise<void> {
    const key = this._key(serverId, secretName);
    await this._secrets.delete(key);
  }

  /** Store a generic extension-level secret. */
  async setGlobalSecret(name: string, value: string): Promise<void> {
    await this._secrets.store(`mcpGrid.global.${name}`, value);
  }

  /** Retrieve a generic extension-level secret. */
  async getGlobalSecret(name: string): Promise<string | undefined> {
    return this._secrets.get(`mcpGrid.global.${name}`);
  }

  /** Delete a generic extension-level secret. */
  async deleteGlobalSecret(name: string): Promise<void> {
    await this._secrets.delete(`mcpGrid.global.${name}`);
  }

  private _key(serverId: string, secretName: string): string {
    return `mcpGrid.${serverId}.${secretName}`;
  }
}
