import type { McpServer } from '@prisma/client';
import type { ServerEnvEntry } from '../validation/mcp-server.schema.js';

/**
 * Minimal dependency surface for the env resolver: anything that can turn a
 * (secretName, key) pair into a string. Matches `SecretService.resolve()` so
 * resolution now flows through the configured SecretBackend driver instead
 * of reading `Secret.data` directly.
 */
export interface SecretResolver {
  resolve(secretName: string, key: string): Promise<string>;
}

/**
 * Resolve a server's env entries into a flat key-value map.
 * - Inline `value` entries are used directly.
 * - `valueFrom.secretRef` entries are looked up through the resolver.
 * Throws if a referenced secret or key is missing.
 */
export async function resolveServerEnv(
  server: McpServer,
  resolver: SecretResolver,
): Promise<Record<string, string>> {
  const entries = server.env as ServerEnvEntry[];
  if (!entries || entries.length === 0) return {};

  const result: Record<string, string> = {};

  for (const entry of entries) {
    if (entry.value !== undefined) {
      result[entry.name] = entry.value;
    } else if (entry.valueFrom?.secretRef) {
      const { name: secretName, key } = entry.valueFrom.secretRef;
      try {
        result[entry.name] = await resolver.resolve(secretName, key);
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        throw new Error(
          `Cannot resolve secret for server '${server.name}' env '${entry.name}': ${msg}`,
        );
      }
    }
  }

  return result;
}
