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

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
sqlc_out="$root/services/worker/internal/storage/postgres/sqlc"

snapshot_dir="$(mktemp -d)"
trap 'rm -rf "$snapshot_dir"' EXIT

snapshot_sqlc="$snapshot_dir/sqlc"
mkdir -p "$snapshot_sqlc"

if [ -d "$sqlc_out" ]; then
  cp -R "$sqlc_out/." "$snapshot_sqlc/"
fi

"$root/bin/worker-storage-gen"

drift=0

if ! diff -ru "$snapshot_sqlc" "$sqlc_out" >/dev/null; then
  echo "worker-storage-check: Generated sqlc output drift detected under $sqlc_out" >&2
  diff -ru "$snapshot_sqlc" "$sqlc_out" >&2 || true
  drift=1
fi

if [ "$drift" -ne 0 ]; then
  echo "worker-storage-check: run bin/worker-storage-gen and commit the regenerated output" >&2
  exit 1
fi
