#!/bin/bash

# Save the piped message to temp file
TEMP_MSG=$(mktemp)
cat > "$TEMP_MSG"

# Extract Message-ID more robustly
MESSAGE_ID=$(grep -i "^Message-ID:" "$TEMP_MSG" | head -1 | sed 's/^[Mm]essage-[Ii][Dd]: *//; s/^<//; s/>$//' | tr -d '\r\n ')

# Cleanup temp file
rm "$TEMP_MSG"

if [ -z "$MESSAGE_ID" ]; then
    notify-send "Error" "Could not find Message-ID"
    exit 1
fi

# Get file path from notmuch
FILEPATH=$(notmuch search --output=files "id:$MESSAGE_ID" 2>/dev/null | head -1)

if [ -z "$FILEPATH" ] || [ ! -f "$FILEPATH" ]; then
    # Try alternative search
    FILEPATH=$(notmuch search --output=files --exclude=false "*" 2>/dev/null | xargs grep -l "Message-ID.*$MESSAGE_ID" 2>/dev/null | head -1)
fi

if [ -z "$FILEPATH" ] || [ ! -f "$FILEPATH" ]; then
    notify-send "Error" "File not found for Message-ID: $MESSAGE_ID"
    exit 1
fi

# Move to Trash folder
TRASH_DIR="$HOME/.local/share/mail/Trash/cur"
mkdir -p "$TRASH_DIR"

FILENAME=$(basename "$FILEPATH")
mv "$FILEPATH" "$TRASH_DIR/$FILENAME"

# Update notmuch database
notmuch new --no-hooks >/dev/null 2>&1

# Tag as deleted
notmuch tag +deleted +trash -inbox -unread -- "id:$MESSAGE_ID" >/dev/null 2>&1

# Trigger sync in background
(sleep 2 && mbsync -a 2>&1 | grep -v CLOSE >/dev/null) &

notify-send "📧 Aerc" "Moved to Trash"
