#!/bin/bash
# NORDABIZ DATA QUALITY DEPLOYMENT SCRIPT
# Date: 2026-01-02
# Changes: 38 approved fixes

set -e
echo "============================================================"
echo "NORDABIZ DATA QUALITY DEPLOYMENT"
echo "============================================================"

# Configuration
DB_USER="nordabiz_app"
DB_NAME="nordabiz"
APP_DIR="/var/www/nordabiznes"

# Step 1: Backup
echo "STEP 1: Creating backup..."
BACKUP_FILE="$HOME/backup_before_data_quality_$(date +%Y%m%d_%H%M%S).sql"
sudo -u www-data pg_dump -U $DB_USER $DB_NAME > "$BACKUP_FILE"
echo "✓ Backup: $BACKUP_FILE"

# Step 2: Execute SQL
echo "STEP 2: Executing SQL scripts..."
sudo -u www-data psql -U $DB_USER -d $DB_NAME -f "$APP_DIR/priority1_category_fixes.sql"
sudo -u www-data psql -U $DB_USER -d $DB_NAME -f "$APP_DIR/priority1_keyword_updates.sql"
sudo -u www-data psql -U $DB_USER -d $DB_NAME -f "$APP_DIR/priority2_services_insert.sql"

# Step 3: Restart
echo "STEP 3: Restarting application..."
sudo systemctl restart nordabiznes
sudo systemctl status nordabiznes --no-pager | head -3

echo "✓ DEPLOYMENT COMPLETE"
