import { normalizeDatabaseBinding } from "../runner/execution-config.mjs";
import { normalizeOptionalString, normalizeTemplateInputs, normalizeTemplateLifecycleSteps } from "./runtime.mjs";

const DEFAULT_LOCAL_IMAGE = "pgvector/pgvector:pg16";
const DEFAULT_LOCAL_USER = "testkit";
const DEFAULT_LOCAL_PASSWORD = "testkit";

export function normalizeDatabaseConfig(explicitService, serviceName) {
  if (explicitService.databaseFrom) return undefined;
  if (!explicitService.database) return undefined;

  const database =
    explicitService.database.provider === "local"
      ? explicitService.database
      : {
          provider: "local",
          ...explicitService.database,
        };

  return {
    ...database,
    binding: normalizeDatabaseBinding(database.binding || "per-runtime", `Service "${serviceName}" database.binding`),
    provider: "local",
    selectedBackend: "local",
    reset: database.reset !== false,
    image: database.image || DEFAULT_LOCAL_IMAGE,
    user: database.user || DEFAULT_LOCAL_USER,
    password: database.password || DEFAULT_LOCAL_PASSWORD,
    template: normalizeDatabaseTemplateConfig(database.template, serviceName),
    serviceName,
  };
}

export function normalizeDatabaseTemplateConfig(value, serviceName) {
  if (value == null) {
    return {
      inputs: [],
      migrate: [],
      seed: [],
      verify: [],
    };
  }
  if (!value || typeof value !== "object") {
    throw new Error(`Service "${serviceName}" database.template must be an object`);
  }

  return {
    inputs: normalizeTemplateInputs(value.inputs, `Service "${serviceName}" database.template`),
    migrate: normalizeTemplateLifecycleSteps(value.migrate, `Service "${serviceName}" database.template.migrate`),
    seed: normalizeTemplateLifecycleSteps(value.seed, `Service "${serviceName}" database.template.seed`),
    verify: normalizeTemplateLifecycleSteps(value.verify, `Service "${serviceName}" database.template.verify`),
  };
}
