# -*- coding: utf-8 -*-
"""P5-W3 본론(V75~V78) 스모크 테스트 — 로그인 후 신규 엔드포인트 검증"""
import json
import urllib.request

BASE = "http://localhost:8082"


def call(method, path, token=None, body=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(BASE + path, data=data, method=method)
    req.add_header("Content-Type", "application/json")
    if token:
        req.add_header("Authorization", "Bearer " + token)
    try:
        with urllib.request.urlopen(req, timeout=15) as r:
            return r.status, json.loads(r.read().decode())
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read().decode() or "{}")


# 1. 로그인
for pw in ["admin1234!", "admin1234", "admin"]:
    st, bd = call("POST", "/api/auth/login", body={"loginId": "admin", "password": pw})
    if st == 200 and bd.get("success"):
        token = bd["data"]["accessToken"]
        print("[LOGIN] OK (pw=%s) roles=%s" % (pw, bd["data"].get("roles")))
        break
else:
    print("[LOGIN] FAIL: %s %s" % (st, bd))
    raise SystemExit(1)

# 2. 신규 + 회귀 엔드포인트 GET 검증
endpoints = [
    "/api/accounting-closes",
    "/api/year-end-statements",
    "/api/forecast-kpi",
    "/api/retention-anomalies",
    "/api/agent-annual-incomes",
    "/api/accounting-entries",
    "/api/withholding-tax-reports",
    "/api/vat-reports",
]
ok = 0
for ep in endpoints:
    st, bd = call("GET", ep, token)
    success = st == 200 and bd.get("success")
    cnt = ""
    if success and isinstance(bd.get("data"), dict) and "list" in bd["data"]:
        cnt = " (list=%d)" % len(bd["data"]["list"])
    print("  [%s] GET %s -> %s%s" % ("PASS" if success else "FAIL", ep, st, cnt))
    if success:
        ok += 1

print("\n[RESULT] %d/%d endpoints PASS" % (ok, len(endpoints)))
