#!/bin/bash
# =============================================================================
# Mark Old Migrations as Applied
# =============================================================================
# Run this script when the database was set up before migration tracking existed.
# This marks old migrations as "applied" so only new migrations will run.
# Usage: ./scripts/mark-migrations-applied.sh
# =============================================================================

set -e

# Configuration - adjust these if needed
COMPOSE_FILES="-f docker-compose.yml -f docker-compose.prod.yml --env-file .env.production"

echo "Marking old migrations as applied in migration_history..."

docker compose $COMPOSE_FILES exec -T mongodb mongosh --quiet --eval '
db = db.getSiblingDB("accessible_video");

// Create migration_history collection if it does not exist
db.createCollection("migration_history");

// Mark old migrations as already applied
var oldMigrations = [
  {version: "2025-08-17-120000", description: "Initial database schema with users, jobs, and audit_logs collections"},
  {version: "2025-08-17-120001", description: "Index optimization"},
  {version: "2025-08-17-120002", description: "Audit log schema update"},
  {version: "2025-10-10-000000", description: "Add auth_provider field to users"},
  {version: "2025-10-10-000001", description: "Update user schema validator for production role and nullable passwords"}
];

oldMigrations.forEach(function(m) {
  db.migration_history.updateOne(
    {version: m.version},
    {$setOnInsert: {version: m.version, description: m.description, applied_at: new Date()}},
    {upsert: true}
  );
  print("Marked as applied: " + m.version);
});

print("");
print("Done. Current migration history:");
db.migration_history.find().sort({version: 1}).forEach(printjson);
'

echo ""
echo "Old migrations marked as applied. You can now run ./scripts/deploy.sh"
