#!/bin/bash
set -e

# Function to create database if not exists
create_database() {
    local database=$1
    echo "Creating database: $database"
    psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
        SELECT 'CREATE DATABASE $database'
        WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '$database')\gexec
EOSQL
}

# Create all required databases
for db in rwa_identity rwa_wallet rwa_mpc rwa_backup rwa_planting rwa_referral rwa_reward rwa_leaderboard rwa_reporting rwa_authorization rwa_admin rwa_presence rwa_blockchain rwa_transfer; do
    create_database "$db"
done

echo "All databases created successfully!"

# =============================================================================
# Configure PostgreSQL for Debezium CDC (Logical Replication)
# =============================================================================
echo "Configuring PostgreSQL for Debezium CDC..."

# Set wal_level to logical for CDC support
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
    -- Set wal_level to logical (requires restart to take effect)
    ALTER SYSTEM SET wal_level = 'logical';

    -- Increase max_replication_slots for Debezium
    ALTER SYSTEM SET max_replication_slots = 4;

    -- Increase max_wal_senders for replication connections
    ALTER SYSTEM SET max_wal_senders = 4;

    -- Create replication user for Debezium (if not exists)
    DO \$\$
    BEGIN
        IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'debezium') THEN
            CREATE ROLE debezium WITH REPLICATION LOGIN PASSWORD 'debezium_password';
        END IF;
    END
    \$\$;

    -- Grant connect to identity and referral databases
    GRANT CONNECT ON DATABASE rwa_identity TO debezium;
    GRANT CONNECT ON DATABASE rwa_referral TO debezium;
EOSQL

# Grant schema permissions on rwa_identity
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "rwa_identity" <<-EOSQL
    -- Grant usage on public schema
    GRANT USAGE ON SCHEMA public TO debezium;

    -- Grant select on all tables (current and future)
    GRANT SELECT ON ALL TABLES IN SCHEMA public TO debezium;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO debezium;
EOSQL

# Grant schema permissions on rwa_referral
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "rwa_referral" <<-EOSQL
    -- Grant usage on public schema
    GRANT USAGE ON SCHEMA public TO debezium;

    -- Grant select on all tables (current and future)
    GRANT SELECT ON ALL TABLES IN SCHEMA public TO debezium;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO debezium;
EOSQL

echo "PostgreSQL CDC configuration completed!"
echo "NOTE: PostgreSQL restart is required for wal_level change to take effect."
