#!/bin/bash
# Attach a file to a gantt board task
# Usage: ./attach-file.sh <task-id> <file-path>

SUPABASE_URL="https://qnatchrjlpehiijwtreh.supabase.co"
SERVICE_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InFuYXRjaHJqbHBlaGlpand0cmVoIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc3MTY0MDQzNiwiZXhwIjoyMDg3MjE2NDM2fQ.rHoc3NfL59S4lejU4-ArSzox1krQkQG-TnfXb6sslm0"

HEADERS=(-H "apikey: $SERVICE_KEY" -H "Authorization: Bearer $SERVICE_KEY" -H "Content-Type: application/json")

TASK_ID="$1"
FILE_PATH="$2"

if [[ -z "$TASK_ID" || -z "$FILE_PATH" ]]; then
    echo "Usage: $0 <task-id> <file-path>"
    exit 1
fi

if [[ ! -f "$FILE_PATH" ]]; then
    echo "Error: File not found: $FILE_PATH"
    exit 1
fi

FILENAME=$(basename "$FILE_PATH")
# Determine MIME type based on extension
EXTENSION="${FILENAME##*.}"
case "$EXTENSION" in
    md|markdown) MIME_TYPE="text/markdown" ;;
    txt) MIME_TYPE="text/plain" ;;
    json) MIME_TYPE="application/json" ;;
    pdf) MIME_TYPE="application/pdf" ;;
    png) MIME_TYPE="image/png" ;;
    jpg|jpeg) MIME_TYPE="image/jpeg" ;;
    gif) MIME_TYPE="image/gif" ;;
    *) MIME_TYPE="application/octet-stream" ;;
esac

# Convert file to base64 data URL
BASE64_CONTENT=$(base64 -i "$FILE_PATH" | tr -d '\n')
DATA_URL="data:$MIME_TYPE;base64,$BASE64_CONTENT"

# Generate attachment ID and timestamp
ATTACHMENT_ID=$(uuidgen | tr '[:upper:]' '[:lower:]')
NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
FILE_SIZE=$(stat -f%z "$FILE_PATH")

# Get current task attachments
echo "Fetching current task..."
CURRENT_ATTACHMENTS=$(curl -s "$SUPABASE_URL/rest/v1/tasks?id=eq.$TASK_ID&select=attachments" "${HEADERS[@]}" | jq 'if type == "array" then .[0].attachments // [] else .attachments // [] end')

# Create new attachment object (field names must match UI expectations)
NEW_ATTACHMENT=$(jq -n \
    --arg id "$ATTACHMENT_ID" \
    --arg name "$FILENAME" \
    --arg type "$MIME_TYPE" \
    --argjson size "$FILE_SIZE" \
    --arg dataUrl "$DATA_URL" \
    --arg uploadedAt "$NOW" \
    '{
        id: $id,
        name: $name,
        type: $type,
        size: $size,
        dataUrl: $dataUrl,
        uploadedAt: $uploadedAt
    }')

# Merge with existing attachments
UPDATED_ATTACHMENTS=$(echo "$CURRENT_ATTACHMENTS" | jq --argjson new "$NEW_ATTACHMENT" '. + [$new]')

# Update task
echo "Attaching file to task..."
curl -s -X PATCH "$SUPABASE_URL/rest/v1/tasks?id=eq.$TASK_ID" \
    "${HEADERS[@]}" \
    -d "{\"attachments\": $UPDATED_ATTACHMENTS, \"updated_at\": \"$NOW\"}" | jq '.'

echo ""
echo "✅ Attached: $FILENAME"
echo "   Size: $FILE_SIZE bytes"
echo "   Type: $MIME_TYPE"
