import json
import urllib.request
import base64
import os

# Config
API_URL = "http://192.168.178.6:8090/ce/api"
USER = "admin"
PASS = "gemini"

def get_auth_header():
    auth_str = f"{USER}:{PASS}"
    b64_auth = base64.b64encode(auth_str.encode()).decode()
    return {"Authorization": f"Basic {b64_auth}", "Content-Type": "application/json"}

def test_create():
    print(f"Testing Create against {API_URL}...")
    
    # 1. Random Name to ensure new creation
    import random
    company_name = f"Test Company {random.randint(1000,9999)}"
    
    payload = {
        "name": company_name,
        "city": "Berlin",
        "country": "DE"
    }
    
    req = urllib.request.Request(
        f"{API_URL}/companies",
        data=json.dumps(payload).encode('utf-8'),
        headers=get_auth_header(),
        method="POST"
    )
    
    try:
        with urllib.request.urlopen(req) as response:
            if response.status == 200:
                data = json.loads(response.read().decode())
                print(f"✅ SUCCESS: Created Company '{company_name}'")
                print(f"   ID: {data.get('id')}")
                print(f"   Name: {data.get('name')}")
                return data.get('id')
            else:
                print(f"❌ FAILED: Status {response.status}")
                print(response.read().decode())
    except Exception as e:
        print(f"❌ EXCEPTION: {e}")
        return None

def test_find(company_id):
    if not company_id: return
    
    print(f"\nVerifying creation via GET /companies/{company_id}...")
    req = urllib.request.Request(
        f"{API_URL}/companies/{company_id}",
        headers=get_auth_header(),
        method="GET"
    )
    try:
        with urllib.request.urlopen(req) as response:
            data = json.loads(response.read().decode())
            print(f"✅ VERIFIED: Found company in DB.")
    except Exception as e:
        print(f"❌ VERIFICATION FAILED: {e}")

if __name__ == "__main__":
    cid = test_create()
    test_find(cid)
