#!/bin/sh
set -e

# ---------------------------------------------------------------------------
# 1. Resolve any previously failed migrations so deploy can proceed.
#    Only migrations explicitly marked as "Failed" in the status output are
#    resolved. We grep for lines containing "Failed" and extract the name.
# ---------------------------------------------------------------------------
echo "[migrate] Checking for failed migrations..."
STATUS_OUTPUT=$(bunx prisma migrate status 2>&1 || true)
echo "$STATUS_OUTPUT"

# Only resolve migrations whose status line explicitly says "Failed"
echo "$STATUS_OUTPUT" | grep -i "failed" | grep -oE '[0-9]{14}_[a-zA-Z_]+' | while read -r MIGRATION; do
  echo "[migrate] Resolving failed migration: $MIGRATION"
  bunx prisma migrate resolve --rolled-back "$MIGRATION" || true
done

# ---------------------------------------------------------------------------
# 2. Deploy all pending migrations from the migrations directory.
# ---------------------------------------------------------------------------
echo "[migrate] Running prisma migrate deploy..."
bunx prisma migrate deploy
