import type { EnvVar } from './types.js';

const envVars = new Map<string, EnvVar>();

export async function getEnvVars(): Promise<EnvVar[]> {
  return Array.from(envVars.values()).sort((a, b) => a.name.localeCompare(b.name));
}

export async function getEnvVar(id: string): Promise<EnvVar | null> {
  return envVars.get(id) ?? null;
}

export async function upsertEnvVar(input: Partial<EnvVar> & { name: string }): Promise<EnvVar> {
  const id = input.id || input.name.toLowerCase().replace(/[^a-z0-9_]+/g, '_');
  const envVar: EnvVar = {
    id,
    name: input.name,
    value: input.isSecret ? 'REDACTED' : input.value ?? '',
    isSecret: input.isSecret ?? true,
    source: input.source ?? 'local',
    azureKeyVaultName: input.azureKeyVaultName,
    azureSecretName: input.azureSecretName,
    updatedAt: new Date().toISOString(),
  };
  envVars.set(id, envVar);
  return envVar;
}

export async function deleteEnvVar(id: string): Promise<boolean> {
  return envVars.delete(id);
}
