#!/usr/bin/env bash

set -eo pipefail

# Prefer app executables
app_root="$(cd "$(dirname "$0")/.."; pwd)"
export PATH="$app_root/bin:$PATH"

step() {
  local spin=false
  if [[ $1 == "--spin" ]] ; then
    spin=true
    spin_title=$2
    shift
    shift
  fi
  local step_name="$1"
  shift

  gum style --foreground 135 --bold "▸ $step_name"
  gum style --foreground 240 "$*"

  if $spin; then
    gum spin --spinner dot --title "$spin_title" --show-error -- "$@"
  else
    "$@"
  fi

  local exit_code=$?
  echo
  return $exit_code
}

echo
# Check if any migration or schema files have changed between origin/main and current working tree
changed_files=$(git diff --name-only origin/main...HEAD -- 'db/migrate/*' 'db/schema.rb' 'db/schema_cache.yml')

# If no relevant files changed, exit successfully
if [ -z "$changed_files" ]; then
  gum style --foreground 240 "No migration or schema files changed. Skipping audit."
  exit 0
fi

gum style --foreground 135 --bold "Migration or schema files changed:"
gum style --foreground 240 "$changed_files"
echo

step "Deleting schema files" rm -f db/untenanted_schema.rb db/schema.rb db/schema_cache.yml

step "Deleting tenant directory" rm -rf storage/tenants/development/686465299

step --spin "Migrating..." "Regenerating schema files" bin/rails db:migrate ARTENANT=686465299

# Check if the schema files have any git changes
if git diff --quiet -- db/schema.rb db/schema_cache.yml; then
  gum style --foreground 46 "✓ Schema files are in sync with migrations"
  exit 0
else
  echo
  gum style --foreground 196 --bold "✗ Schema files are out of sync with migrations!"
  echo
  gum style --foreground 135 --bold "Differences:"
  git --no-pager diff -- db/schema.rb db/schema_cache.yml
  exit 1
fi
