#!/bin/bash

echo "🚀 Starting database backup process..."

# Check environment argument
if [ -z "$1" ]; then
  echo "❌ Please provide an environment (e.g., development, staging, production)."
  exit 1
fi

# Set environment file based on argument
ENV_FILE=".env.$1"
if [ ! -f "$ENV_FILE" ]; then
  echo "❌ Environment file $ENV_FILE not found!"
  exit 1
fi

# Clean CRLF line endings from the env file (in case it was edited on Windows)
sed -i 's/\r$//' "$ENV_FILE"

# Load environment variables
set -a
source "$ENV_FILE"
set +a

# Read the tables array (second argument)
TABLES_STRING="$2"
CHILD_PROCESS_SLUG="$3"

# Clean TABLES_STRING from [ and ] and spaces (handle both "users,orders" and ["users","orders"])
TABLES_STRING_CLEAN=$(echo "$TABLES_STRING" | sed 's/\[//g' | sed 's/\]//g' | sed 's/ //g')

# Convert to array
IFS=',' read -r -a TABLES <<< "$TABLES_STRING_CLEAN"

# Create timestamped folder
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FOLDER="public/backup/${TIMESTAMP}"
mkdir -p "$BACKUP_FOLDER"

# File path variable
BACKUP_FILE=""
LOG_FILE="$BACKUP_FOLDER/pg_dump_output.log"

# Backup function for specific tables (SQL data-only)
backup_specific_tables() {
  echo "🔵 Backing up specific tables: ${TABLES[@]}"

  TABLE_LIST=""
  for table in "${TABLES[@]}"; do
    TABLE_LIST+=" -t $table"
  done

  BACKUP_FILE="$BACKUP_FOLDER/selected_tables_backup.sql"

  echo "Running pg_dump with the following command (data-only SQL)..."

  # Data-only SQL dump
  PGPASSWORD=$DATABASE_PASSWORD pg_dump -h "$DATABASE_HOST" -p "$DATABASE_PORT" -U "$DATABASE_USER" -d "$DATABASE_NAME" $TABLE_LIST --data-only --column-inserts --file="$BACKUP_FILE" > "$LOG_FILE" 2>&1

  # Check if the backup was successful
  if [ $? -eq 0 ]; then
    echo "✅ Backup completed successfully at $BACKUP_FILE."
    return 0
  else
    echo "❌ Backup failed. Check the log file for details: $LOG_FILE"
    return 1
  fi
}

# Backup function for the full database (SQL data-only)
backup_entire_db() {
  echo "🟢 Backing up the full database..."
  BACKUP_FILE="$BACKUP_FOLDER/full_db_backup.sql"

  PGPASSWORD=$DATABASE_PASSWORD pg_dump -h "$DATABASE_HOST" -p "$DATABASE_PORT" -U "$DATABASE_USER" -d "$DATABASE_NAME" --data-only --column-inserts --file="$BACKUP_FILE" > "$LOG_FILE" 2>&1

  if [ $? -eq 0 ]; then
    echo "✅ Backup completed successfully at $BACKUP_FILE."
    return 0
  else
    echo "❌ Backup failed. Check the log file for details: $LOG_FILE"
    return 1
  fi
}

# Decision point to determine if we're backing up full DB or specific tables
if [ -z "$TABLES_STRING_CLEAN" ]; then
  backup_entire_db
  BACKUP_STATUS=$?
else
  backup_specific_tables
  BACKUP_STATUS=$?
fi

# Insert log in child_process_logs based on backup status
if [ $BACKUP_STATUS -eq 0 ]; then
  PGPASSWORD=$DATABASE_PASSWORD psql -h "$DATABASE_HOST" -U "$DATABASE_USER" -d "$DATABASE_NAME" -p "$DATABASE_PORT" <<EOF

INSERT INTO child_process_logs (
    child_process_id,
    downloadables,
    process_status,
    output,
    initiated_by,
    created_at
)
SELECT
    id,
    '$BACKUP_FILE',
    'success',
    'backup completed successfully',
    1,
    NOW()
FROM
    child_processes
WHERE
    slug = '$CHILD_PROCESS_SLUG';
EOF

  if [ $? -eq 0 ]; then
    echo "✅ child_processes.downloadables updated and log inserted for slug: $CHILD_PROCESS_SLUG"
    echo "<link>$BACKUP_FILE<link>"
  else
    echo "❌ Failed to update child_processes or insert log entry."
  fi
else
  PGPASSWORD=$DATABASE_PASSWORD psql -h "$DATABASE_HOST" -U "$DATABASE_USER" -d "$DATABASE_NAME" -p "$DATABASE_PORT" <<EOF

INSERT INTO child_process_logs (
    child_process_id,
    downloadables,
    process_status,
    output,
    initiated_by,
    created_at
)
SELECT
    id,
    '',
    'failed',
    'backup failed - check logs at $LOG_FILE',
    1,
    NOW()
FROM
    child_processes
WHERE
    slug = '$CHILD_PROCESS_SLUG';
EOF

  echo "❌ Backup failed. Log inserted with failure status."
fi
