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

# 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 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_customer_list():
    """Test customer list view"""
    session = requests.Session()
    
    if not login(session):
        return "✗ Failed to login"
    
    response = session.get(f"{base_url}/customers", verify=False)
    if response.status_code != 200:
        return f"✗ Failed to access customers page: Status {response.status_code}"
    
    content = response.text
    
    # Check for expected customers
    expected_customers = ["Müller GmbH", "Test Customer", "Schröder Süßwaren AG", "Björn Köhler"]
    found_customers = []
    
    for customer in expected_customers:
        if customer in content:
            found_customers.append(customer)
    
    if len(found_customers) > 0:
        return f"✓ Customer list loaded successfully ({len(found_customers)} customers found)"
    else:
        return "✗ No customers found in list"

def test_edit_customer():
    """Test editing a customer"""
    session = requests.Session()
    
    if not login(session):
        return "✗ Failed to login"
    
    # Get a customer ID to edit (let's find "Test Customer")
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
        "-c", "SELECT id FROM customers WHERE name = 'Test Customer' LIMIT 1;"
    ], capture_output=True, text=True)
    
    customer_id = result.stdout.strip()
    if not customer_id:
        return "✗ Failed to find test customer"
    
    # Test GET edit page
    response = session.get(f"{base_url}/customer/edit/{customer_id}", verify=False)
    if response.status_code != 200:
        return f"✗ Failed to access customer edit page: Status {response.status_code}"
    
    # Check if customer data and licenses are displayed
    content = response.text
    if "Test Customer" not in content:
        return "✗ Edit page doesn't show customer data"
    
    # Update customer data
    updated_data = {
        "name": "Test Customer GmbH & Co. KG",
        "email": "updated@testcustomer.de"
    }
    
    response = session.post(f"{base_url}/customer/edit/{customer_id}", 
                           data=updated_data, 
                           verify=False, 
                           allow_redirects=False)
    
    if response.status_code == 302 and response.headers.get('Location') == '/customers':
        return "✓ Customer edited successfully"
    else:
        return f"✗ Failed to edit customer: Status {response.status_code}"

def test_delete_customer():
    """Test deleting a customer"""
    session = requests.Session()
    
    if not login(session):
        return "✗ Failed to login"
    
    # Create a test customer without licenses
    test_customer = {
        "customer_name": "Löschtest Firma GmbH",
        "email": "delete@löschtest.de",
        "license_key": "TEMP-KEY-DELETE",
        "license_type": "Test",
        "valid_from": "2025-01-01",
        "valid_until": "2025-01-02"
    }
    
    # Create customer with license
    session.post(f"{base_url}/", data=test_customer, verify=False, allow_redirects=False)
    
    # Get the customer ID
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
        "-c", "SELECT id FROM customers WHERE name = 'Löschtest Firma GmbH';"
    ], capture_output=True, text=True)
    
    customer_id = result.stdout.strip()
    if not customer_id:
        return "✗ Failed to create test customer"
    
    # First, try to delete customer with license (should fail)
    response = session.post(f"{base_url}/customer/delete/{customer_id}", 
                          verify=False, 
                          allow_redirects=False)
    
    # Check if customer still exists (should not be deleted due to license)
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
        "-c", f"SELECT COUNT(*) FROM customers WHERE id = {customer_id};"
    ], capture_output=True, text=True)
    
    if int(result.stdout.strip()) != 1:
        return "✗ Customer with licenses was incorrectly deleted"
    
    # Now delete the license first
    subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
        "-c", f"DELETE FROM licenses WHERE customer_id = {customer_id};"
    ], capture_output=True)
    
    # Try to delete customer again (should work now)
    response = session.post(f"{base_url}/customer/delete/{customer_id}", 
                          verify=False, 
                          allow_redirects=False)
    
    # Verify deletion
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
        "-c", f"SELECT COUNT(*) FROM customers WHERE id = {customer_id};"
    ], capture_output=True, text=True)
    
    if int(result.stdout.strip()) == 0:
        return "✓ Customer deletion works correctly (protects customers with licenses)"
    else:
        return "✗ Failed to delete customer without licenses"

# Rebuild and restart admin panel
print("Rebuilding admin panel with customer management...")
subprocess.run(["docker-compose", "build", "admin-panel"], capture_output=True)
subprocess.run(["docker-compose", "up", "-d", "admin-panel"], capture_output=True)
print("Waiting for container to start...")
subprocess.run(["sleep", "5"], capture_output=True)

print("\nTesting Customer Management Functionality")
print("=" * 50)

# Test customer list
print("\n1. Testing Customer List:")
print("-" * 30)
list_result = test_customer_list()
print(list_result)

# Test edit functionality
print("\n2. Testing Customer Edit:")
print("-" * 30)
edit_result = test_edit_customer()
print(edit_result)

# Verify the edit
print("\nVerifying edited customer:")
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", 
    "-c", "SELECT name, email FROM customers WHERE name LIKE 'Test Customer%';"
], capture_output=True, text=True)
print(result.stdout)

# Test delete functionality
print("\n3. Testing Customer Delete:")
print("-" * 30)
delete_result = test_delete_customer()
print(delete_result)

# Show customer statistics
print("\n" + "=" * 50)
print("Customer Statistics:")
print("-" * 50)
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", 
    "-c", """SELECT c.name, COUNT(l.id) as total_licenses, 
             COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses
             FROM customers c
             LEFT JOIN licenses l ON c.id = l.customer_id
             GROUP BY c.name
             ORDER BY c.name;"""
], capture_output=True, text=True)
print(result.stdout)