#!/bin/bash
# sql/helper_scripts/verify_rollup.sh
# ============================================================================
# SQL ROLLUP VERIFICATION SCRIPT
# ============================================================================
# Purpose:
# This script verifies that the 'master_schema_rollup.sql' file is an exact
# concatenation of the individual SQL component files. This helps ensure
# that all database setup scripts are synchronized.
#
# Usage:
# From the root of the project, run:
#   bash sql/verify_rollup.sh
#
# The script will exit with code 0 if they match, and 1 if they don't.
# ============================================================================

# Set the script to exit immediately if a command fails
set -e

# Define file paths relative to the project root
SQL_DIR="sql"
MASTER_FILE="$SQL_DIR/master_schema_rollup.sql"

# The individual files to concatenate, IN ORDER.
SOURCE_FILES=(
    "$SQL_DIR/initial_schema.sql"
    "$SQL_DIR/initial_data.sql"
    "$SQL_DIR/initial_triggers_and_functions.sql"
)

# Create a temporary file to hold the concatenated content
TEMP_FILE=$(mktemp)

# Ensure the temporary file is removed when the script exits
trap 'rm -f "$TEMP_FILE"' EXIT

# Concatenate all source files into the temp file
echo "Concatenating source files into a temporary file..."
cat "${SOURCE_FILES[@]}" > "$TEMP_FILE"

echo "Comparing concatenated content with '$MASTER_FILE'..."

# Use 'diff' to compare the master file with the temporary concatenated file.
# The '-q' flag makes diff quiet and just exit with a status code.
if diff -q "$MASTER_FILE" "$TEMP_FILE"; then
    echo "✅ Success: '$MASTER_FILE' is up to date with the individual SQL files."
    exit 0
else
    echo "❌ Error: '$MASTER_FILE' is out of sync. Differences found."
    echo "To see the differences, run: diff -u \"$MASTER_FILE\" <(cat ${SOURCE_FILES[@]})"
    exit 1
fi
