#!/bin/bash
# notify-add-indexes.sh - Add recommended indexes to Notify SQLite database
# Usage: ./notify-add-indexes.sh [db_path] [--cleanup]
#
# Options:
#   --cleanup    Also drops the now-redundant message_by_time index
#
# Default path for Flatpak: ~/.var/app/com.ranfdev.Notify/data/com.ranfdev.Notify.sqlite
# Default path for local build: ~/.local/share/com.ranfdev.Notify.sqlite
#
# Usage:
#./notify-add-indexes.sh                                    # Just add indexes
#./notify-add-indexes.sh --cleanup                         # Add indexes + remove old one
#./notify-add-indexes.sh ~/.local/share/com.ranfdev.Notify.sqlite --cleanup
DB_PATH=""
CLEANUP=false
# Parse arguments
for arg in "$@"; do
    case $arg in
        --cleanup)
            CLEANUP=true
            ;;
        *)
            DB_PATH="$arg"
            ;;
    esac
done
DB_PATH="${DB_PATH:-$HOME/.var/app/com.ranfdev.Notify/data/com.ranfdev.Notify.sqlite}"
if [ ! -f "$DB_PATH" ]; then
    echo "Error: Database not found at $DB_PATH"
    exit 1
fi
echo "Database: $DB_PATH"
echo ""
# Create composite index for message(server, topic) - used by delete_messages
echo "Creating message_server_topic index..."
sqlite3 "$DB_PATH" "CREATE INDEX IF NOT EXISTS message_server_topic ON message(server, topic);"
# Create covering index for list_messages query
echo "Creating message_list_covering index..."
sqlite3 "$DB_PATH" "CREATE INDEX IF NOT EXISTS message_list_covering ON message(server, topic, data ->> '\$.time');"
# Optional: drop redundant index
if [ "$CLEANUP" = true ]; then
    echo ""
    echo "Dropping redundant message_by_time index..."
    sqlite3 "$DB_PATH" "DROP INDEX IF EXISTS message_by_time;"
fi
# Verify
echo ""
echo "Current indexes:"
sqlite3 "$DB_PATH" "SELECT name FROM sqlite_master WHERE type='index' ORDER BY name;"
echo ""
echo "Done!"
