import { _setSecret, _getSecret, _deleteSecret, _isKeyringAvailable } from "agency-lang/stdlib-lib/keyring.js"

/** @module
  Store and retrieve secrets in the operating system's keyring, so API keys
  and tokens never touch plaintext files.

  ```ts
  import { setSecret, getSecret, deleteSecret, isKeyringAvailable } from "std::auth/keyring"

  node main() {
    if (isKeyringAvailable()) {
      setSecret("my-api-key", "sk-abc123")
      const key = getSecret("my-api-key")
      print(key)
      deleteSecret("my-api-key")
    }
  }
  ```

  On macOS this uses the Keychain, and on Linux the Secret Service. Windows is
  not yet supported, so fall back to environment variables there. Secrets live
  under the "agency-lang" service name unless you pass a custom `service`.
*/

effect std::setSecret { key: string, service: string }
effect std::getSecret { key: string, service: string }
effect std::deleteSecret { key: string, service: string }

export def setSecret(key: string, value: string, service: string = "agency-lang"): Result {
  """
  Store a secret in the system keyring, overwriting any existing value for the same key.

  @param key - The secret key name
  @param value - The secret value to store
  @param service - Keyring namespace the secret is stored under
  """
  return interrupt std::setSecret("Are you sure you want to store a secret in the system keyring?", {
    key: key,
    service: service
  })

  destructive {
    return try _setSecret(key, value, service)
  }
}

export def getSecret(key: string, service: string = "agency-lang"): Result {
  """
  Retrieve a secret from the system keyring. Returns the secret value, or null if not found.

  @param key - The secret key name
  @param service - Keyring namespace to read from
  """
  return interrupt std::getSecret("Are you sure you want to read a secret from the system keyring?", {
    key: key,
    service: service
  })

  return try _getSecret(key, service)
}

export def deleteSecret(key: string, service: string = "agency-lang"): Result {
  """
  Delete a secret from the system keyring. Returns true if deleted, false if the key did not exist.

  @param key - The secret key name
  @param service - Keyring namespace to delete from
  """
  return interrupt std::deleteSecret("Are you sure you want to delete a secret from the system keyring?", {
    key: key,
    service: service
  })

  destructive {
    return try _deleteSecret(key, service)
  }
}

export def isKeyringAvailable(): boolean {
  """
  Check if the system keyring is available on this platform. Returns true on macOS and on Linux with secret-tool installed, false otherwise.
  """
  return _isKeyringAvailable()
}
