#!/usr/bin/env python3
"""Test admin auth flow"""
import urllib.request, json, ssl

ctx = ssl.create_default_context()

# Step 1: Mock login to get token
print("=== 1. Mock Login ===")
data = json.dumps({"employee_id": "admin001"}).encode()
req = urllib.request.Request("https://itsupport.servyou.com.cn/api/h5/mock-login", data=data, method="POST")
req.add_header("Content-Type", "application/json")
try:
    resp = urllib.request.urlopen(req, context=ctx, timeout=10)
    body = json.loads(resp.read().decode())
    token = body["data"]["token"]
    print(f"Status: {resp.status}")
    print(f"Token: {token}")
    print(f"Employee: {body['data'].get('employee_name')}")
except urllib.request.HTTPError as e:
    body = json.loads(e.read().decode())
    print(f"Error {e.code}: {json.dumps(body, ensure_ascii=False)}")
    token = None

if token:
    # Step 2: Try to access admin dashboard with token
    print("\n=== 2. Admin Dashboard (with token) ===")
    req2 = urllib.request.Request("https://itsupport.servyou.com.cn/api/admin/dashboard/overview")
    req2.add_header("Authorization", f"Bearer {token}")
    try:
        resp = urllib.request.urlopen(req2, context=ctx, timeout=10)
        print(f"Status: {resp.status}")
        body = json.loads(resp.read().decode())
        print(f"Code: {body.get('code')}")
        print(f"Message: {body.get('message')}")
        if body.get("data"):
            print(f"Data keys: {list(body['data'].keys())}")
    except urllib.request.HTTPError as e:
        body = json.loads(e.read().decode())
        print(f"Status {e.code}: {json.dumps(body, ensure_ascii=False)}")

    # Step 3: List agents
    print("\n=== 3. List Agents ===")
    req3 = urllib.request.Request("https://itsupport.servyou.com.cn/api/admin/agents")
    req3.add_header("Authorization", f"Bearer {token}")
    try:
        resp = urllib.request.urlopen(req3, context=ctx, timeout=10)
        print(f"Status: {resp.status}")
        body = json.loads(resp.read().decode())
        print(f"Code: {body.get('code')}")
        print(f"Data: {json.dumps(body.get('data'), ensure_ascii=False)[:300]}")
    except urllib.request.HTTPError as e:
        body = json.loads(e.read().decode())
        print(f"Status {e.code}: {json.dumps(body, ensure_ascii=False)}")
