#!/bin/bash
# Database setup script for BookBeach

# Database connection parameters
DB_HOST="localhost"
DB_PORT="5432"
DB_NAME="bookbeach"
DB_USER="postgres"
DB_PASSWORD="F@f@k0s!!"

echo "Setting up BookBeach database..."

# Check if PostgreSQL is running
if ! pg_isready -h $DB_HOST -p $DB_PORT >/dev/null 2>&1; then
    echo "Error: PostgreSQL is not running on $DB_HOST:$DB_PORT"
    echo "Please start PostgreSQL service and try again."
    exit 1
fi

# Test connection
echo "Testing database connection..."
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d postgres -c "\l" >/dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "Error: Cannot connect to PostgreSQL with provided credentials"
    exit 1
fi

# Check if database exists, create if not
echo "Checking if database '$DB_NAME' exists..."
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d postgres -lqt | cut -d \| -f 1 | grep -qw $DB_NAME
if [ $? -ne 0 ]; then
    echo "Creating database '$DB_NAME'..."
    PGPASSWORD=$DB_PASSWORD createdb -h $DB_HOST -p $DB_PORT -U $DB_USER $DB_NAME
    if [ $? -ne 0 ]; then
        echo "Error: Failed to create database '$DB_NAME'"
        exit 1
    fi
    echo "Database '$DB_NAME' created successfully."
else
    echo "Database '$DB_NAME' already exists."
fi

# Run table creation script
echo "Creating database tables..."
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -f "01_create_tables.sql"
if [ $? -ne 0 ]; then
    echo "Error: Failed to create tables"
    exit 1
fi
echo "Tables created successfully."

# Run initial data script
echo "Inserting initial data..."
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -f "02_initial_data.sql"
if [ $? -ne 0 ]; then
    echo "Error: Failed to insert initial data"
    exit 1
fi
echo "Initial data inserted successfully."

echo "Database setup completed successfully!"
echo ""
echo "Database Details:"
echo "  Host: $DB_HOST"
echo "  Port: $DB_PORT"
echo "  Database: $DB_NAME"
echo "  User: $DB_USER"
echo ""
echo "You can now connect to the database and start using BookBeach!"