#!/bin/bash
# update-contracts.sh
#
# Updates the payload-contracts repo with fresh types from the CMS.
# Run this after modifying collections or blocks and regenerating types.
#
# Usage:
#   ./scripts/update-contracts.sh           # Extract, build, and prompt for commit
#   ./scripts/update-contracts.sh --push    # Also push to GitHub

set -e

CMS_DIR="$(cd "$(dirname "$0")/.." && pwd)"
CONTRACTS_DIR="/home/payload/payload-contracts"
PAYLOAD_TYPES="$CMS_DIR/src/payload-types.ts"

echo "=== Update Payload Contracts ==="
echo ""

# 1. Verify payload-types.ts exists
if [ ! -f "$PAYLOAD_TYPES" ]; then
  echo "ERROR: $PAYLOAD_TYPES not found."
  echo "Run: pnpm payload generate:types"
  exit 1
fi

# 2. Verify contracts repo exists
if [ ! -d "$CONTRACTS_DIR" ]; then
  echo "ERROR: $CONTRACTS_DIR not found."
  echo "Clone: git clone https://github.com/complexcaresolutions/payload-contracts.git $CONTRACTS_DIR"
  exit 1
fi

# 3. Run type extraction
echo "[1/3] Extracting types..."
cd "$CONTRACTS_DIR"
npx tsx scripts/extract-types.ts "$PAYLOAD_TYPES"

# 4. Build to verify
echo ""
echo "[2/3] Building..."
pnpm build

echo ""
echo "[3/3] Checking for changes..."
cd "$CONTRACTS_DIR"

if git diff --quiet && git diff --cached --quiet; then
  echo "No changes detected."
  exit 0
fi

echo ""
echo "Changes detected:"
git diff --stat
echo ""

# 5. Commit
read -p "Commit message (or 'skip'): " MSG
if [ "$MSG" != "skip" ] && [ -n "$MSG" ]; then
  git add -A
  git commit -m "$MSG"

  if [ "$1" = "--push" ]; then
    echo "Pushing to GitHub..."
    git push
    echo "Done! Contracts updated and pushed."
  else
    echo "Committed locally. Run 'cd $CONTRACTS_DIR && git push' to publish."
  fi
else
  echo "Skipped commit. Changes are unstaged."
fi
