#!/bin/bash

BASE_URL="https://consoleapi.inficomsolutions.in/public/api" 

# reuse known admin credentials or create new
EMAIL="admin$(date +%s)@test.com"
PASSWORD="password123"

# Register & Login
curl -s -X POST "$BASE_URL/auth/register" -H "Content-Type: application/json" -d "{\"name\":\"Notes Checker\", \"email\":\"$EMAIL\", \"password\":\"$PASSWORD\"}" > /dev/null
LOGIN_RES=$(curl -s -X POST "$BASE_URL/auth/login" -H "Content-Type: application/json" -d "{\"email\":\"$EMAIL\", \"password\":\"$PASSWORD\"}")
TOKEN=$(echo $LOGIN_RES | grep -o '"token":"[^"]*' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "FAILED: No token."
  exit 1
fi

# 1. Create a Note on Console ID 1 (Assuming it exists, or let's create one first to be safe)
# Shortcut: Just create note on RDP ID 1 (It should exist from previous tests, or we fail if DB empty)
# Better: Create new object.
RDP_RES=$(curl -s -X POST "$BASE_URL/rdp" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"ip_address":"8.8.8.8", "username":"u", "password":"p"}')
RDP_ID=$(echo $RDP_RES | grep -o '"id":[^,}]*' | cut -d':' -f2 | tr -d ' ' | tr -d '"')

echo "Creating Note for RDP $RDP_ID..."
NOTE_RES=$(curl -s -X POST "$BASE_URL/notes" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"model_type\":\"rdp\", \"model_id\":$RDP_ID, \"note\":\"Important RDP Note\"}")

echo "Create Note Response: $NOTE_RES"

# 2. List Notes
echo "Fetching Notes..."
LIST_RES=$(curl -s -X GET "$BASE_URL/notes?model_type=rdp&model_id=$RDP_ID" \
  -H "Authorization: Bearer $TOKEN")

echo "$LIST_RES"

if [[ $LIST_RES == *"Important RDP Note"* ]]; then
    echo "SUCCESS: Note created and retrieved."
else
    echo "FAILED: Note not found."
    exit 1
fi
