#!/usr/bin/env bash
# delete-thread.sh <thread_id>
#
# Deletes a Discord thread (channel) via the Discord REST API.
# Reads the bot token from projects/discord-bot/.env (DISCORD_TOKEN=...).
#
# Exit codes:
#   0 — deleted (HTTP 200 or 204)
#   1 — bad args, token not found, or API error

set -euo pipefail

THREAD_ID="${1:-}"
if [ -z "$THREAD_ID" ]; then
    echo "[ERROR] Usage: delete-thread.sh <thread_id>" >&2
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="$SCRIPT_DIR/../.env"

if [ ! -f "$ENV_FILE" ]; then
    echo "[ERROR] .env not found at $ENV_FILE" >&2
    exit 1
fi

# Extract token — handles quoted and unquoted values, ignores inline comments
DISCORD_TOKEN=$(grep '^DISCORD_TOKEN=' "$ENV_FILE" \
    | head -1 \
    | sed 's/^DISCORD_TOKEN=//' \
    | sed "s/[\"']//g" \
    | sed 's/#.*//' \
    | tr -d '[:space:]')

if [ -z "$DISCORD_TOKEN" ]; then
    echo "[ERROR] DISCORD_TOKEN not found or empty in $ENV_FILE" >&2
    exit 1
fi

RESP=$(curl -s -o /tmp/discord_delete_resp.txt -w "%{http_code}" \
    -X DELETE \
    "https://discord.com/api/v10/channels/${THREAD_ID}" \
    -H "Authorization: Bot ${DISCORD_TOKEN}" \
    -H "Content-Type: application/json")

HTTP_CODE="$RESP"
BODY=$(cat /tmp/discord_delete_resp.txt 2>/dev/null || echo "")
rm -f /tmp/discord_delete_resp.txt

if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "204" ]; then
    echo "[OK] Thread ${THREAD_ID} deleted (HTTP ${HTTP_CODE})"
    exit 0
else
    echo "[ERROR] Delete failed: HTTP ${HTTP_CODE} — ${BODY}" >&2
    exit 1
fi
