import { DefaultAzureCredential } from "@azure/identity"
import { KeyVaultSecret, SecretClient } from "@azure/keyvault-secrets"

let client: SecretClient | null = null

function getClient(): SecretClient {
  if (!client) {
    const keyVaultName: string = process.env["KEY_VAULT_NAME"]
    if (!keyVaultName) throw new Error("KEY_VAULT_NAME is empty")
    const kvUri: string = `https://${keyVaultName}.vault.azure.net`
    const credential: DefaultAzureCredential = new DefaultAzureCredential()
    client = new SecretClient(kvUri, credential)
  }
  return client
}

async function getSecret(secretName: string): Promise<string> {
  const secretClient = getClient()
  const secret: KeyVaultSecret = await secretClient.getSecret(secretName)
  return secret.value
}

export async function getGithubAppPrivateKey(): Promise<string> {
  return await getSecret("github-app-private-key-0")
}

export async function getGithubAppWebhookSecret(): Promise<string> {
  return await getSecret("github-app-webhook-secret-1")
}

export async function getCFAPIJWTPrivateKey(): Promise<string> {
  return await getSecret("cf-api-jwt-private-key-0")
}

export async function getCFAPIJWTPublicKey(): Promise<string> {
  return await getSecret("cf-api-jwt-public-key-0")
}
