#!/bin/bash

BASE_URL="https://consoleapi.inficomsolutions.in/public/api" 
APP_URL="https://example.com" # Should return 200

# 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\":\"Cron Tester\", \"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

# Create RDP -> Browser -> Email -> Console
RDP_RES=$(curl -s -X POST "$BASE_URL/rdp" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"ip_address":"1.1.1.1", "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\":\"B1\"}")
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\":\"e@e.com\", \"email_password\":\"p\"}")
CONSOLE_ID=$(echo $EMAIL_RES | grep -o '"console_id":[^,}]*' | cut -d':' -f2 | tr -d ' ' | tr -d '"')

# Create dummy files
echo "PK..." > dummy.zip
echo "dummy jks" > dummy.jks

# Create App (Status: uploaded)
APP_RES=$(curl -s -X POST "$BASE_URL/app" \
  -H "Authorization: Bearer $TOKEN" \
  -F "console_id=$CONSOLE_ID" \
  -F "app_name=Cron Test App" \
  -F "app_link=$APP_URL" \
  -F "app_code_zip=@dummy.zip" \
  -F "jks_file=@dummy.jks")
APP_ID=$(echo $APP_RES | grep -o '"id":[^,}]*' | cut -d':' -f2 | tr -d ' ' | tr -d '"')

# Set App to 'in_review' manually via DB or API update call (API allows status update)
curl -s -X PUT "$BASE_URL/app/$APP_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"status":"in_review"}' > /dev/null

echo "App Created ($APP_ID) and set to 'in_review'. Link: $APP_URL"

# Run Cron Script
echo "Running Cron Script..."
php cron/check_app_status.php

# Verify App Status
APP_DATA=$(curl -s -X GET "$BASE_URL/app?console_id=$CONSOLE_ID" \
  -H "Authorization: Bearer $TOKEN")
STATUS=$(echo $APP_DATA | grep -o '"status":"[^"]*' | cut -d'"' -f4)

echo "App Status After Cron: $STATUS"

if [ "$STATUS" == "published" ]; then
    echo "SUCCESS: App status updated by Cron."
else
    echo "FAILED: App status not updated."
    exit 1
fi
