#!/usr/bin/env python3
import requests
import urllib3
import subprocess
import json

# Disable SSL warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

base_url = "https://localhost:443"
admin_user = {"username": "rac00n", "password": "1248163264"}

def login(session):
    """Login to admin panel"""
    login_data = {
        "username": admin_user["username"],
        "password": admin_user["password"]
    }
    response = session.post(f"{base_url}/login", data=login_data, verify=False, allow_redirects=False)
    return response.status_code == 302

def test_json_logging():
    """Test JSON value logging in audit log"""
    session = requests.Session()
    login(session)
    
    print("Testing JSON Value Storage in Audit Log")
    print("=" * 50)
    
    # 1. Create a license (should log new_values as JSON)
    print("\n1. Creating license to test JSON logging...")
    license_data = {
        "customer_name": "JSON Test GmbH",
        "email": "json@test.de",
        "license_key": "JSON-TEST-KEY",
        "license_type": "full",
        "valid_from": "2025-01-01",
        "valid_until": "2025-12-31"
    }
    response = session.post(f"{base_url}/create", data=license_data, verify=False, allow_redirects=False)
    print("✓ License created")
    
    # 2. Get the license ID
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
        "-c", "SELECT id FROM licenses WHERE license_key = 'JSON-TEST-KEY';"
    ], capture_output=True, text=True)
    license_id = result.stdout.strip()
    
    if license_id:
        # 3. Edit the license (should log both old_values and new_values)
        print("\n2. Editing license to test old/new JSON values...")
        
        # First get the edit page to ensure we have the right form
        response = session.get(f"{base_url}/license/edit/{license_id}", verify=False)
        
        # Now update
        updated_data = {
            "license_key": "JSON-TEST-UPDATED",
            "license_type": "test",
            "valid_from": "2025-01-01",
            "valid_until": "2025-06-30",
            "is_active": "on"
        }
        response = session.post(f"{base_url}/license/edit/{license_id}", 
                              data=updated_data, 
                              verify=False, 
                              allow_redirects=False)
        print("✓ License updated")
    
    # 4. Check the audit log for JSON values
    print("\n3. Checking audit log for JSON values...")
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
        "-c", """SELECT action, entity_type, 
                 CASE WHEN old_values IS NULL THEN 'NULL' 
                      ELSE jsonb_pretty(old_values) END as old_vals,
                 CASE WHEN new_values IS NULL THEN 'NULL' 
                      ELSE jsonb_pretty(new_values) END as new_vals
                 FROM audit_log 
                 WHERE entity_type IN ('license', 'customer')
                 AND (old_values IS NOT NULL OR new_values IS NOT NULL)
                 ORDER BY timestamp DESC 
                 LIMIT 5;"""
    ], capture_output=True, text=True)
    
    print(result.stdout)
    
    # 5. Test specific JSON queries
    print("\n4. Testing JSON queries...")
    
    # Query for specific license key in new_values
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
        "-c", """SELECT COUNT(*) 
                 FROM audit_log 
                 WHERE new_values->>'license_key' LIKE 'JSON%';"""
    ], capture_output=True, text=True)
    
    count = int(result.stdout.strip())
    if count > 0:
        print(f"✓ Found {count} entries with JSON license keys")
    
    # Query for updates (where both old and new values exist)
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
        "-c", """SELECT COUNT(*) 
                 FROM audit_log 
                 WHERE old_values IS NOT NULL 
                 AND new_values IS NOT NULL;"""
    ], capture_output=True, text=True)
    
    update_count = int(result.stdout.strip())
    print(f"✓ Found {update_count} UPDATE entries with both old and new values")
    
    # 6. Clean up test data
    print("\n5. Cleaning up test data...")
    subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
        "-c", "DELETE FROM licenses WHERE license_key LIKE 'JSON%';"
    ], capture_output=True)
    print("✓ Test data cleaned up")

# Run the test
test_json_logging()