#!/bin/bash

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

# Login
EMAIL="admin$(date +%s)@test.com"
PASSWORD="password123"
curl -s -X POST "$BASE_URL/auth/register" -H "Content-Type: application/json" -d "{\"name\":\"Archiver\", \"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)

# Create objects
RDP_RES=$(curl -s -X POST "$BASE_URL/rdp" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"ip_address":"9.9.9.9", "username":"u", "password":"p"}')
RDP_ID=$(echo $RDP_RES | grep -o '"id":[^,}]*' | cut -d':' -f2 | tr -d ' ' | tr -d '"')

BROWSER_RES=$(curl -s -X POST "$BASE_URL/browser" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d "{\"rdp_id\":$RDP_ID, \"browser_name\":\"B_SOLD\"}")
BROWSER_ID=$(echo $BROWSER_RES | grep -o '"id":[^,}]*' | cut -d':' -f2 | tr -d ' ' | tr -d '"')

EMAIL_RES=$(curl -s -X POST "$BASE_URL/email" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d "{\"browser_id\":$BROWSER_ID, \"email\":\"sold@e.com\", \"email_password\":\"p\"}")
CONSOLE_ID=$(echo $EMAIL_RES | grep -o '"console_id":[^,}]*' | cut -d':' -f2 | tr -d ' ' | tr -d '"')

echo "Console Created For Sale: $CONSOLE_ID"

# Update to SOLD
echo "Marking Console as SOLD..."
SOLD_RES=$(curl -s -X PUT "$BASE_URL/console/$CONSOLE_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"status":"sold"}')

echo "Response: $SOLD_RES"

# Verify deletion from active tables
echo "Checking active console table..."
GET_RES=$(curl -s -X GET "$BASE_URL/console/$CONSOLE_ID" -H "Authorization: Bearer $TOKEN")
if [[ $GET_RES == *"not found"* ]]; then
    echo "SUCCESS: Console deleted from active tables."
else
    echo "FAILED: Console still exists in active tables."
    exit 1
fi

# Verify archive (Manual MySQL check in script)
echo "Verifying archive in database..."
mysql -u inficoms2_consoleUser -p'ybKYnn~1zcM*r11h' inficoms2_console -e "SELECT * FROM sold_consoles WHERE console_id = $CONSOLE_ID" | grep "sold@e.com"

if [ $? -eq 0 ]; then
    echo "SUCCESS: Console record found in sold_consoles archive."
else
    echo "FAILED: Console record not found in archive."
    exit 1
fi

echo "Archive features verified."
