#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
out_dir="${repo_root}/internal/generatedmodels"

resolve_relspec() {
  if [[ -n "${RELSPEC:-}" ]]; then
    printf '%s' "${RELSPEC}"
    return
  fi
  if command -v relspec >/dev/null 2>&1; then
    printf '%s' "relspec"
    return
  fi
  if [[ -x "${HOME}/go/bin/relspec" ]]; then
    printf '%s' "${HOME}/go/bin/relspec"
    return
  fi

  echo "relspec not found; install git.warky.dev/wdevs/relspecgo/cmd/relspec@latest" >&2
  exit 1
}

relspec_bin="$(resolve_relspec)"

cd "${repo_root}"

mapfile -t schema_files < <(find schema -maxdepth 1 -type f -name '*.dbml' | sort)
if [[ "${#schema_files[@]}" -eq 0 ]]; then
  echo "No DBML schema files found in schema/" >&2
  exit 1
fi

schema_list="$(IFS=,; echo "${schema_files[*]}")"

rm -rf "${out_dir}"
mkdir -p "${out_dir}"

"${relspec_bin}" convert \
  --from dbml \
  --from-list "${schema_list}" \
  --to bun \
  --to-path "${out_dir}" \
  --package generatedmodels

# relspec currently emits a few files with unused fmt imports; strip only when fmt is unused.
for file in "${out_dir}"/*.go; do
  sed -i 's/fmt.Sprintf("%d", m.ID)/fmt.Sprintf("%v", m.ID)/g' "${file}"

  if ! grep -q 'fmt\.' "${file}"; then
    sed -i '/^[[:space:]]*"fmt"$/d' "${file}"
  fi
done

bash "${repo_root}/scripts/patch-generated-models.sh"

gofmt -w "${out_dir}"/*.go
