#!/usr/bin/env python3
import requests
import urllib3
from datetime import datetime, timedelta

# Disable SSL warnings for self-signed certificate
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

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

def test_license_creation():
    """Test creating a license through the admin panel"""
    session = requests.Session()
    
    # Login first
    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)
    if response.status_code != 302:
        return "Failed to login"
    
    # Create a test license
    license_data = {
        "customer_name": "Test Customer",
        "email": "test@example.com",
        "license_key": "TEST-LICENSE-KEY-123",
        "license_type": "premium",
        "valid_from": datetime.now().strftime("%Y-%m-%d"),
        "valid_until": (datetime.now() + timedelta(days=365)).strftime("%Y-%m-%d")
    }
    
    response = session.post(f"{base_url}/", data=license_data, verify=False, allow_redirects=False)
    
    if response.status_code == 302 and response.headers.get('Location') == '/':
        return "✓ License created successfully"
    else:
        return f"✗ Failed to create license: {response.status_code}"

print("Testing License Creation")
print("=" * 40)
result = test_license_creation()
print(result)

# Verify the license was created in the database
import subprocess
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", 
    "-c", "SELECT c.name, l.license_key, l.license_type, l.valid_from, l.valid_until FROM licenses l JOIN customers c ON l.customer_id = c.id;"
], capture_output=True, text=True)

print("\nLicenses in database:")
print(result.stdout)