#!/bin/bash
###############################################################################
# Clear Test Data Script
#
# This script clears test users and dealers from the development database.
# Run this manually when you need a clean slate for testing registration.
#
# Usage: bash pc-scripts/clear-test-data.sh
###############################################################################

set -e

echo ""
echo "==================================================================="
echo "  Clearing Test Data from Database"
echo "==================================================================="
echo ""

# Load environment variables from .env and .env.local (same order as Next.js)
# Using 'set -a' to automatically export all variables
if [ -f ".env" ]; then
  set -a
  source .env
  set +a
fi
if [ -f ".env.local" ]; then
  set -a
  source .env.local
  set +a
fi

# Step 0: Rotate NEXTAUTH_SECRET to invalidate all JWT sessions
echo "Step 0: Rotating NEXTAUTH_SECRET to invalidate JWT sessions..."
echo ""

# Generate new random secret (base64 encoded, 32 bytes = 256 bits)
NEW_SECRET=$(openssl rand -base64 32)

# Update .env.local with new secret
if [ -f ".env.local" ]; then
  # Check if NEXTAUTH_SECRET exists in .env.local
  if grep -q "^NEXTAUTH_SECRET=" .env.local; then
    # Use different delimiter (|) since secret contains = and other special chars
    sed -i.bak "s|^NEXTAUTH_SECRET=.*|NEXTAUTH_SECRET=\"$NEW_SECRET\"|" .env.local
    echo "✓ Rotated NEXTAUTH_SECRET in .env.local"
    echo "  (This invalidates all browser JWT cookies, forcing re-authentication)"
  else
    # NEXTAUTH_SECRET not found - append it
    echo "NEXTAUTH_SECRET=\"$NEW_SECRET\"" >> .env.local
    echo "✓ Added NEXTAUTH_SECRET to .env.local"
  fi
else
  echo "⚠ Warning: .env.local not found, cannot rotate NEXTAUTH_SECRET"
  echo "  JWT sessions will NOT be invalidated!"
fi

echo ""

# Extract database credentials from DATABASE_URL
# Format: postgresql://user:password@host:port/database
if [ -n "$DATABASE_URL" ]; then
  DB_USER=$(echo "$DATABASE_URL" | sed -n 's|postgresql://\([^:]*\):.*|\1|p')
  DB_PASSWORD=$(echo "$DATABASE_URL" | sed -n 's|postgresql://[^:]*:\([^@]*\)@.*|\1|p')
  DB_HOST=$(echo "$DATABASE_URL" | sed -n 's|postgresql://[^@]*@\([^:]*\):.*|\1|p')
  DB_NAME=$(echo "$DATABASE_URL" | sed -n 's|.*/\([^?]*\).*|\1|p')
else
  # Fallback to hardcoded values if DATABASE_URL not set
  DB_PASSWORD='rVFpybL00%TsVqkG'
  DB_USER='amsoil_dev'
  DB_NAME='acdev3_amsoil_dlp_dev'
  DB_HOST='localhost'
fi

# Note: Using TRUNCATE CASCADE for complete cleanup (development only!)
# This clears ALL data from ALL tables, ensuring no orphaned records or partial data

echo "Step 1: Clearing ALL data from database tables (TRUNCATE CASCADE)..."
echo "  This will delete ALL users, dealers, accounts, and webhook events."
echo ""

# TRUNCATE with CASCADE automatically handles foreign key dependencies
# Order doesn't matter with CASCADE, but listing for clarity:
# 1. StripeWebhookEvent (no dependencies)
# 2. Dealer (depends on User)
# 3. Account (depends on User)
# 4. User (root table)

psql "$DATABASE_URL" -c "
TRUNCATE TABLE \"StripeWebhookEvent\",
               \"Dealer\",
               \"Account\",
               \"User\"
CASCADE;"

echo "✓ All tables cleared successfully"

echo ""
echo "==================================================================="
echo "✓ Test data cleared successfully"
echo "==================================================================="
echo ""
echo "Cleared:"
echo "  - Rotated NEXTAUTH_SECRET (invalidates all JWT session cookies)"
echo "  - Test users (timothy@aimclear.com, t.d.eastvold@gmail.com)"
echo "  - Associated dealer accounts"
echo "  - NextAuth OAuth accounts (prevents stale OAuth data)"
echo "  - Webhook event history (for clean webhook testing)"
echo ""
echo "Note: You will need to sign in again since all JWT cookies are invalidated."
echo ""
