#!/bin/bash
# Load fixtures into the database
# Usage: ./fixtures/load.sh [--reset]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# Load environment variables
if [ -f "$PROJECT_DIR/.env" ]; then
    export $(grep -v '^#' "$PROJECT_DIR/.env" | xargs)
fi

DB_USER="${POSTGRES_USER:-root}"
DB_NAME="${POSTGRES_DB:-inventory}"
CONTAINER="${DB_CONTAINER:-inventory-db-1}"

echo "Loading fixtures into $DB_NAME..."

# Check if --reset flag is passed
if [ "$1" == "--reset" ]; then
    echo "Resetting database (truncating all tables)..."
    docker exec -i "$CONTAINER" psql -U "$DB_USER" -d "$DB_NAME" -c "
        DO \$\$ DECLARE
            r RECORD;
        BEGIN
            FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename != 'doctrine_migration_versions') LOOP
                EXECUTE 'TRUNCATE TABLE ' || quote_ident(r.tablename) || ' CASCADE';
            END LOOP;
        END \$\$;
    "
fi

# Load fixtures with foreign key checks disabled
docker exec -i "$CONTAINER" psql -U "$DB_USER" -d "$DB_NAME" <<EOF
SET session_replication_role = replica;
$(cat "$SCRIPT_DIR/data.sql")
SET session_replication_role = DEFAULT;
EOF

echo "Fixtures loaded successfully!"
