import { z } from "zod";

export interface VaultConfig {
  address: string;
  token: string;
}

export class VaultClient {
  constructor(private config: VaultConfig) {}

  async readSecret<T>(path: string, schema: z.ZodSchema<T>): Promise<T> {
    const url = `${this.config.address}/v1/${path}`;
    const res = await fetch(url, {
      headers: {
        "X-Vault-Token": this.config.token,
      },
    });
    if (!res.ok) {
      throw new Error(`Vault request failed with status ${res.status}`);
    }
    const body = await res.json();
    const data = body.data?.data ?? body.data;
    return schema.parse(data);
  }
}

export const createVaultClient = (): VaultClient => {
  const address = process.env.VAULT_ADDR;
  const token = process.env.VAULT_TOKEN;
  if (!address || !token) {
    throw new Error("Vault configuration is missing");
  }
  return new VaultClient({ address, token });
};
