import { SecretManagerServiceClient } from "@google-cloud/secret-manager";

const client = new SecretManagerServiceClient();

const SECRET_PREFIX = "projects/xtablo/secrets/";
const SECRET_SUFFIX = "/versions/latest";

/**
 * fetchSecret retrieves the latest version of the secret from secret manager.
 * @param {string} tokenName The name of the secret in Secret Manager
 * @return {string} The sensitive value stored in Secret Manager.
 */
async function fetchSecret(tokenName) {
  const [version] = await client.accessSecretVersion({
    name: SECRET_PREFIX + tokenName + SECRET_SUFFIX,
  });
  return version.payload.data.toString();
}

export type Secrets = {
  supabaseServiceRoleKey: string;
  supabaseConnectionString: string;
  supabaseCaCert: string;
  emailClientSecret: string;
  emailRefreshToken: string;
  r2AccessKeyId: string;
  r2SecretAccessKey: string;
  // Env dependent
  streamChatApiSecret: string;
  stripeSecretKey: string;
  stripeWebhookSecret: string;
  // Staging
  streamChatApiSecretStaging: string;
  stripeSecretKeyStaging: string;
  stripeWebhookSecretStaging: string;
};

/**
 * loadSecrets retrieves all the secrets needed for the program
 * @return {object} The object with all of the secrets
 */
export async function loadSecrets(): Promise<Secrets> {
  const secrets = {
    supabaseServiceRoleKey: await fetchSecret("supabase-service-role-key"),
    supabaseConnectionString: await fetchSecret("supabase-connection-string"),
    supabaseCaCert: await fetchSecret("supabase-ca-cert"),
    emailClientSecret: await fetchSecret("email-client-secret"),
    emailRefreshToken: await fetchSecret("email-refresh-token"),
    r2AccessKeyId: await fetchSecret("r2-access-key-id"),
    r2SecretAccessKey: await fetchSecret("r2-secret-access-key"),
    // Env dependent
    // Staging
    streamChatApiSecretStaging: await fetchSecret("stream-chat-api-secret-staging"),
    stripeSecretKeyStaging: await fetchSecret("stripe-secret-key-staging"),
    stripeWebhookSecretStaging: await fetchSecret("stripe-webhook-secret-staging"),
    // Production
    streamChatApiSecret: await fetchSecret("stream-chat-api-secret"),
    stripeSecretKey: await fetchSecret("stripe-secret-key"),
    stripeWebhookSecret: await fetchSecret("stripe-webhook-secret"),
  };
  return secrets;
}
