#!/bin/bash
# PostgreSQL Production Initialization Script for CuliUptime
# Run during database initialization for production optimizations

set -e

# Use the database name from environment variable
DB_NAME=${POSTGRES_DB:-culiuptime}

echo "Initializing production optimizations for database: $DB_NAME"

# Connect to the database and run SQL commands
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$DB_NAME" <<-EOSQL
	-- Enable pg_stat_statements extension for query performance monitoring
	CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

	-- Create additional indexes for performance (if not already created by alembic)
	-- These are monitoring-specific optimizations

	-- Index for monitor status queries
	CREATE INDEX IF NOT EXISTS idx_monitors_status_created
	ON monitors(status, created_at DESC);

	-- Index for monitor result timestamp queries
	CREATE INDEX IF NOT EXISTS idx_monitor_results_timestamp
	ON monitor_results(timestamp DESC);

	-- Index for monitor results by monitor_id and timestamp
	CREATE INDEX IF NOT EXISTS idx_monitor_results_monitor_timestamp
	ON monitor_results(monitor_id, timestamp DESC);

	-- Index for notification queries
	CREATE INDEX IF NOT EXISTS idx_notifications_created
	ON notifications(created_at DESC);

	-- Index for user authentication queries
	CREATE INDEX IF NOT EXISTS idx_users_email
	ON users(email);
EOSQL

echo "Running database-level configuration for: $DB_NAME"

# Set up database-level configurations for performance
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$DB_NAME" -c "ALTER DATABASE \"$DB_NAME\" SET timezone = 'UTC';"
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$DB_NAME" -c "ALTER DATABASE \"$DB_NAME\" SET log_statement = 'none';"
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$DB_NAME" -c "ALTER DATABASE \"$DB_NAME\" SET log_min_duration_statement = '1000ms';"

echo "Production initialization completed for database: $DB_NAME"
