import urllib.request
import urllib.error
import json

base_url = "http://localhost:8080/api/v1"

print("--- 1. Test unauthenticated request to Admin endpoint ---")
try:
    req = urllib.request.Request(f"{base_url}/admin/metrics")
    with urllib.request.urlopen(req) as resp:
        print("FAIL: Should not succeed without token")
except urllib.error.HTTPError as e:
    print(f"SUCCESS: Request blocked with HTTP {e.code} ({e.reason})")
    assert e.code == 401

print("\n--- 2. Test login with wrong credentials ---")
try:
    bad_login_data = json.dumps({"username": "admin@tescorisecarrental.com", "password": "wrongpassword"}).encode('utf-8')
    req = urllib.request.Request(f"{base_url}/auth/login", data=bad_login_data, headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req) as resp:
        print("FAIL: Bad password should not succeed")
except urllib.error.HTTPError as e:
    print(f"SUCCESS: Bad credentials rejected with HTTP {e.code}")
    assert e.code == 401

print("\n--- 3. Test login with valid credentials (record DTO) ---")
login_data = json.dumps({
    "username": "admin@tescorisecarrental.com",
    "password": "admin123",
    "rememberMe": True
}).encode('utf-8')
req = urllib.request.Request(f"{base_url}/auth/login", data=login_data, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req) as resp:
    auth_resp = json.loads(resp.read().decode('utf-8'))
    print("SUCCESS: Logged in successfully!")
    print(f"  User: {auth_resp['username']} ({auth_resp['displayName']})")
    print(f"  Role: {auth_resp['role']}")
    print(f"  Token: {auth_resp['token'][:25]}...")
    assert auth_resp['authenticated'] is True
    token = auth_resp['token']

print("\n--- 4. Verify token via /auth/verify ---")
v_req = urllib.request.Request(f"{base_url}/auth/verify", headers={"Authorization": f"Bearer {token}"})
with urllib.request.urlopen(v_req) as resp:
    v_data = json.loads(resp.read().decode('utf-8'))
    print(f"SUCCESS: Token verified. Valid: {v_data['valid']}, User: {v_data['username']}")
    assert v_data['valid'] is True

print("\n--- 5. Access secured Admin endpoint with token ---")
adm_req = urllib.request.Request(f"{base_url}/admin/metrics", headers={"Authorization": f"Bearer {token}"})
with urllib.request.urlopen(adm_req) as resp:
    metrics = json.loads(resp.read().decode('utf-8'))
    print(f"SUCCESS: Admin metrics retrieved: Total Fleet = {metrics['fleet']['totalFleet']}, Bookings = {metrics['totalBookings']}")
    assert metrics['fleet']['totalFleet'] > 0

print("\n--- 6. Test vehicle creation with token ---")
new_veh = json.dumps({
    "make": "Toyota",
    "model": "Land Cruiser 300 VXR VIP",
    "name": "Toyota Land Cruiser 300 VXR VIP",
    "year": "2024",
    "licensePlate": "TESCO-AUTH",
    "category": "SUV / 4x4",
    "seatingCapacity": 7,
    "transmission": "AUTOMATIC",
    "engineType": "DIESEL",
    "color": "Midnight Black",
    "dailyRate": 250.0,
    "minimumDeposit": 400.0,
    "weeklyDiscountPercent": 10.0,
    "vehicleStatus": "AVAILABLE",
    "available": True,
    "featuredImage": "https://tuesday-online-app.s3.us-east-2.amazonaws.com/public/vehicles/fortuner_1741814789.webp"
}).encode('utf-8')
create_req = urllib.request.Request(
    f"{base_url}/admin/vehicles",
    data=new_veh,
    headers={"Content-Type": "application/json", "Authorization": f"Bearer {token}"}
)
with urllib.request.urlopen(create_req) as resp:
    created = json.loads(resp.read().decode('utf-8'))
    print(f"SUCCESS: Admin created vehicle '{created['name']}' (ID: {created['id']})")
    veh_id = created['id']

# Cleanup created vehicle
del_req = urllib.request.Request(
    f"{base_url}/admin/vehicles/{veh_id}",
    headers={"Authorization": f"Bearer {token}"},
    method="DELETE"
)
with urllib.request.urlopen(del_req) as resp:
    del_res = json.loads(resp.read().decode('utf-8'))
    print(f"SUCCESS: Admin cleaned up vehicle ({del_res['message']})")

print("\n--- 7. Logout and revoke token ---")
logout_req = urllib.request.Request(
    f"{base_url}/auth/logout",
    data=b"",
    headers={"Authorization": f"Bearer {token}"}
)
with urllib.request.urlopen(logout_req) as resp:
    logout_res = json.loads(resp.read().decode('utf-8'))
    print(f"SUCCESS: Logout result: {logout_res['message']}")

print("\n--- 8. Verify revoked token can no longer access Admin endpoint ---")
try:
    rev_req = urllib.request.Request(f"{base_url}/admin/metrics", headers={"Authorization": f"Bearer {token}"})
    with urllib.request.urlopen(rev_req) as resp:
        print("FAIL: Revoked token should not be accepted")
except urllib.error.HTTPError as e:
    print(f"SUCCESS: Revoked token correctly rejected with HTTP {e.code}")
    assert e.code == 401

print("\nALL ADMIN AUTHENTICATION TESTS PASSED!")
