#!/bin/bash

# Initialize company_profiles table in Supabase
# Uses Supabase's PostgreSQL connection

echo "🔧 Creating company_profiles table in Supabase..."
echo ""

# Supabase local database connection details
DB_HOST="127.0.0.1"
DB_PORT="54322"
DB_USER="postgres"
DB_PASS="postgres"
DB_NAME="postgres"

# Check if psql is available
if ! command -v psql &> /dev/null; then
    echo "⚠️  psql not found. Installing via Homebrew..."
    brew install postgresql
fi

# Execute the migration SQL
echo "📝 Executing migration SQL..."
PGPASSWORD=$DB_PASS psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME \
  -f supabase/migrations/20251019_create_company_profiles.sql

if [ $? -eq 0 ]; then
    echo ""
    echo "✅ company_profiles table created successfully!"
    echo ""
    echo "🔍 Verifying table..."
    PGPASSWORD=$DB_PASS psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME \
      -c "\d public.company_profiles"
    echo ""
    echo "✅ Table verification complete!"
    echo ""
    echo "💡 You can now run: npm run test:dual-save"
else
    echo ""
    echo "❌ Failed to create table. Error details above."
    echo ""
    echo "💡 Try opening Supabase Studio and running the SQL manually:"
    echo "   http://127.0.0.1:54323"
    exit 1
fi
