#!/usr/bin/env python3
"""E2E: 凭据管理 — 完整 CRUD"""
from helper import *

header("Credentials")

pid = create_project(unique_name("E2E-凭据"))
source_node_id = create_node(pid, "凭据来源节点", "service", "## env leak")["id"]

# ── Create ──
cid = assert_ok(post(f"/api/v1/projects/{pid}/credentials", {
    "label": "DB密码",
    "credential_type": "password",
    "username": "root",
    "secret": "MyS3cret!@#",
    "source_node_id": source_node_id,
    "status": "unverified",
    "notes": "从 Nacos env 拿到的"
}))["id"]
ok("create credential")

# ── List ──
creds = assert_ok(get(f"/api/v1/projects/{pid}/credentials"))
assert len(creds) == 1
c = creds[0]
assert c["label"] == "DB密码"
assert c["credential_type"] == "password"
assert c["secret"] == "MyS3cret!@#"
assert c["source_node_id"] == source_node_id
ok("list credentials (secret plain)")

# ── Create another type ──
cid2 = assert_ok(post(f"/api/v1/projects/{pid}/credentials", {
    "label": "API Token",
    "credential_type": "token",
    "username": "svc-api",
    "secret": "sk-abc123",
    "source_node_id": source_node_id,
    "status": "verified",
    "notes": "API token"
}))["id"]
assert len(assert_ok(get(f"/api/v1/projects/{pid}/credentials"))) == 2
ok("create token credential")

# ── Update ──
assert_ok(put(f"/api/v1/projects/{pid}/credentials/{cid}", {
    "status": "verified",
    "notes": "已验证可用"
}))
creds = assert_ok(get(f"/api/v1/projects/{pid}/credentials"))
c = next(x for x in creds if x["id"] == cid)
assert c["status"] == "verified"
assert c["notes"] == "已验证可用"
ok("update credential status + notes")

# Update secret
assert_ok(put(f"/api/v1/projects/{pid}/credentials/{cid}", {
    "secret": "NewSecret999"
}))
c = next(x for x in assert_ok(get(f"/api/v1/projects/{pid}/credentials")) if x["id"] == cid)
assert c["secret"] == "NewSecret999"
ok("update credential secret")

# Update label, username, and type
assert_ok(put(f"/api/v1/projects/{pid}/credentials/{cid}", {
    "label": "DB密码-更新",
    "credential_type": "token",
    "username": "admin"
}))
c = next(x for x in assert_ok(get(f"/api/v1/projects/{pid}/credentials")) if x["id"] == cid)
assert c["label"] == "DB密码-更新"
assert c["credential_type"] == "token"
assert c["username"] == "admin"
ok("update credential label/type/username")

# ── Delete ──
assert_ok(delete(f"/api/v1/projects/{pid}/credentials/{cid2}"))
assert len(assert_ok(get(f"/api/v1/projects/{pid}/credentials"))) == 1
ok("delete credential")

# ── Invalid cases ──
assert_err(get(f"/api/v1/projects/{pid}/credentials/{cid}"), 405)
ok("individual credential GET not exposed")

assert_err(put(f"/api/v1/projects/{pid}/credentials/00000000-0000-0000-0000-000000000000",
               {"status": "verified"}), 404)
ok("404 on nonexistent credential")

delete_project(pid)

summary()
