#!/bin/bash

# ─────────────────────────────────────────────────────────────
# seed_migrations.sh
# Reads migration filenames from Laravel's migrations directory
# and inserts them into the `migrations` table using Laravel.
# Usage: bash seed_migrations.sh [/path/to/laravel/root]
# ─────────────────────────────────────────────────────────────

LARAVEL_ROOT="${1:-.}"
MIGRATIONS_DIR="$LARAVEL_ROOT/database/migrations"

# ── Sanity checks ─────────────────────────────────────────────
if [ ! -d "$MIGRATIONS_DIR" ]; then
  echo "❌  Migrations directory not found: $MIGRATIONS_DIR"
  exit 1
fi

if [ ! -f "$LARAVEL_ROOT/artisan" ]; then
  echo "❌  Laravel artisan file not found: $LARAVEL_ROOT/artisan"
  exit 1
fi

echo "───────────────────────────────────────────────"
echo "  Laravel Migration Table Seeder"
echo "───────────────────────────────────────────────"
echo "  Using: php artisan tinker"
echo "  Dir: $MIGRATIONS_DIR"
echo "───────────────────────────────────────────────"
echo ""

# ── Collect migration names from filenames ────────────────────
MIGRATION_FILES=()
while IFS= read -r -d '' file; do
  basename=$(basename "$file" .php)
  MIGRATION_FILES+=("$basename")
done < <(find "$MIGRATIONS_DIR" -maxdepth 1 -name "*.php" -print0 | sort -z)

if [ ${#MIGRATION_FILES[@]} -eq 0 ]; then
  echo "⚠️  No migration files found in $MIGRATIONS_DIR"
  exit 0
fi

echo "Found ${#MIGRATION_FILES[@]} migration file(s). Inserting missing ones..."
echo ""

# ── Get current max batch and insert migrations via Laravel ────
cd "$LARAVEL_ROOT"

INSERTED=0
SKIPPED=0

for migration in "${MIGRATION_FILES[@]}"; do
  # Check if migration exists using artisan tinker
  EXISTS=$(php artisan tinker --execute "return DB::table('migrations')->where('migration', '$migration')->exists() ? 1 : 0;" 2>/dev/null | grep -oE '[01]$')

  if [ "$EXISTS" = "1" ]; then
    echo "  ⏭  SKIP    $migration"
    ((SKIPPED++))
  else
    # Get next batch number
    NEXT_BATCH=$(php artisan tinker --execute "return DB::table('migrations')->max('batch') + 1;" 2>/dev/null | grep -oE '[0-9]+$')
    
    # Insert via tinker
    php artisan tinker --execute "DB::table('migrations')->insert(['migration' => '$migration', 'batch' => $NEXT_BATCH]);" 2>/dev/null

    if [ $? -eq 0 ]; then
      echo "  ✅ INSERTED $migration"
      ((INSERTED++))
    else
      echo "  ❌ FAILED   $migration"
    fi
  fi
done

echo ""
echo "───────────────────────────────────────────────"
echo "  Done. Inserted: $INSERTED  |  Skipped: $SKIPPED"
echo "───────────────────────────────────────────────"
