#!/usr/bin/env bash
# test/smoke_test.sh — manual end-to-end smoke test
# Run AFTER the daemon is started:
#   ./bin/archivmail --config config/config.test.yml
#
# Requirements: curl, jq, swaks (apt install swaks)
set -e

BASE="http://localhost:8080"
PASS=0
FAIL=0

ok()   { echo "  ✅  $1"; ((PASS++)); }
fail() { echo "  ❌  $1"; ((FAIL++)); }
sep()  { echo ""; echo "--- $1 ---"; }

# ---- helper ----
get()  { curl -sf -H "Authorization: Bearer $TOKEN" "$BASE$1"; }
post() { curl -sf -X POST -H "Content-Type: application/json" -d "$2" "$BASE$1"; }
postauth() { curl -sf -X POST -H "Content-Type: application/json" \
             -H "Authorization: Bearer $TOKEN" -d "$2" "$BASE$1"; }

sep "Health"
if get /api/health | grep -q '"ok"'; then
  ok "GET /api/health"
else
  fail "GET /api/health"
fi

sep "Auth: Login"
RESP=$(post /api/auth/login '{"username":"admin","password":"adminpass"}')
TOKEN=$(echo "$RESP" | jq -r '.token')
if [ "$TOKEN" != "null" ] && [ -n "$TOKEN" ]; then
  ok "POST /api/auth/login → token received"
else
  fail "POST /api/auth/login"
  echo "Response: $RESP"
  exit 1
fi

sep "Auth: Me"
ME=$(get /api/auth/me)
if echo "$ME" | grep -q '"admin"'; then
  ok "GET /api/auth/me"
else
  fail "GET /api/auth/me: $ME"
fi

sep "Auth: Reject wrong password"
CODE=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"wrongpass"}' \
  "$BASE/api/auth/login")
if [ "$CODE" = "401" ]; then
  ok "Wrong password → 401"
else
  fail "Wrong password → expected 401, got $CODE"
fi

sep "User management"
# Create user
NEW=$(postauth /api/users '{"username":"testuser","email":"test@x.com","password":"testpw","role":"user"}')
UID=$(echo "$NEW" | jq -r '.id')
if [ "$UID" != "null" ] && [ -n "$UID" ]; then
  ok "POST /api/users → created id=$UID"
else
  fail "POST /api/users: $NEW"
fi

# List users
USERS=$(get /api/users)
COUNT=$(echo "$USERS" | jq '. | length')
if [ "$COUNT" -ge 2 ]; then
  ok "GET /api/users → $COUNT users"
else
  fail "GET /api/users → expected ≥2, got $COUNT"
fi

sep "SMTP: Send test mail"
if command -v swaks &>/dev/null; then
  swaks --to archive@localhost --from sender@localhost \
    --server localhost:2525 \
    --header "Subject: Smoke Test Invoice" \
    --body "This is a smoke test mail." \
    --silent 2 && ok "swaks SMTP send" || fail "swaks SMTP send"
  sleep 1  # give indexer time
else
  echo "  ⚠️  swaks not installed, skipping SMTP test (apt install swaks)"
fi

sep "Search"
RESULT=$(get "/api/search?q=smoke")
TOTAL=$(echo "$RESULT" | jq -r '.total // 0')
if [ "$TOTAL" -ge 0 ]; then
  ok "GET /api/search → total=$TOTAL"
else
  fail "GET /api/search: $RESULT"
fi

sep "EML Import"
mkdir -p /tmp/test-eml
cat > /tmp/test-eml/test.eml << 'EML'
From: import@example.com
To: archive@example.com
Subject: Import Test Mail
Date: Thu, 12 Mar 2026 10:00:00 +0000

This mail was imported via CLI.
EML
./bin/archivmail import --config config/config.test.yml /tmp/test-eml/ && \
  ok "archivmail-import" || fail "archivmail-import"

sep "Export"
./bin/archivmail-export --config config/config.test.yml --format eml --out /tmp/test-export/ && \
  ok "archivmail-export (EML)" || fail "archivmail-export (EML)"

sep "Audit Log"
AUDIT=$(get "/api/audit")
ATOTAL=$(echo "$AUDIT" | jq -r '.total // 0')
if [ "$ATOTAL" -gt 0 ]; then
  ok "GET /api/audit → $ATOTAL entries"
else
  fail "GET /api/audit → expected entries, got $ATOTAL"
fi

sep "Logout"
postauth /api/auth/logout '' > /dev/null && ok "POST /api/auth/logout"

# Token should now be rejected
CODE=$(curl -s -o /dev/null -w "%{http_code}" \
  -H "Authorization: Bearer $TOKEN" "$BASE/api/auth/me")
if [ "$CODE" = "401" ]; then
  ok "Token invalid after logout → 401"
else
  fail "Token should be invalid after logout, got $CODE"
fi

# ---- Summary ----
echo ""
echo "========================================"
echo "  Smoke test complete"
echo "  Passed: $PASS  Failed: $FAIL"
echo "========================================"
[ "$FAIL" -eq 0 ]
