#!/bin/bash
set -e

# RelSpec PostgreSQL Integration Tests Runner
# This script starts a PostgreSQL Docker container and runs integration tests

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

echo "=== RelSpec PostgreSQL Integration Tests ==="
echo ""

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Check if docker-compose is available
if ! command -v docker-compose &> /dev/null && ! command -v docker &> /dev/null; then
    echo -e "${RED}Error: docker-compose or docker is not installed${NC}"
    exit 1
fi

# Determine docker compose command
if command -v docker-compose &> /dev/null; then
    DOCKER_COMPOSE="docker-compose"
else
    DOCKER_COMPOSE="docker compose"
fi

# Change to project root
cd "$PROJECT_ROOT"

# Function to cleanup
cleanup() {
    echo -e "\n${YELLOW}Cleaning up...${NC}"
    $DOCKER_COMPOSE down
}

# Trap exit to cleanup
trap cleanup EXIT

# Start PostgreSQL container
echo -e "${YELLOW}Starting PostgreSQL container...${NC}"
$DOCKER_COMPOSE up -d postgres

# Wait for PostgreSQL to be ready
echo -e "${YELLOW}Waiting for PostgreSQL to be ready...${NC}"
max_attempts=30
attempt=0

while [ $attempt -lt $max_attempts ]; do
    if $DOCKER_COMPOSE exec -T postgres pg_isready -U relspec -d relspec_test &> /dev/null; then
        echo -e "${GREEN}PostgreSQL is ready!${NC}"
        break
    fi
    attempt=$((attempt + 1))
    echo -n "."
    sleep 1
done

if [ $attempt -eq $max_attempts ]; then
    echo -e "\n${RED}Error: PostgreSQL failed to start${NC}"
    exit 1
fi

# Give it one more second to fully initialize
sleep 2

# Show database stats
echo -e "\n${YELLOW}Database Information:${NC}"
$DOCKER_COMPOSE exec -T postgres psql -U relspec -d relspec_test -c "
SELECT
    (SELECT COUNT(*) FROM pg_namespace WHERE nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast') AND nspname NOT LIKE 'pg_%') as schemas,
    (SELECT COUNT(*) FROM pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema')) as tables,
    (SELECT COUNT(*) FROM pg_views WHERE schemaname NOT IN ('pg_catalog', 'information_schema')) as views,
    (SELECT COUNT(*) FROM pg_sequences WHERE schemaname NOT IN ('pg_catalog', 'information_schema')) as sequences;
"

# Set environment variable for tests
export RELSPEC_TEST_PG_CONN="postgres://relspec:relspec_test_password@localhost:5439/relspec_test"

echo -e "\n${YELLOW}Running PostgreSQL reader tests...${NC}"
echo "Connection string: $RELSPEC_TEST_PG_CONN"
echo ""

# Run the tests
if go test -v ./pkg/readers/pgsql/ -count=1; then
    echo -e "\n${GREEN}✓ All tests passed!${NC}"
    exit 0
else
    echo -e "\n${RED}✗ Tests failed${NC}"
    exit 1
fi
