"""认证与权限工具"""

import json
from typing import Any

from mcp.types import Tool, TextContent

from trailbase_mcp.client.client import TrailBaseClient


def get_auth_tools() -> list[Tool]:
    """获取认证相关工具"""
    return [
        Tool(
            name="auth.users.list",
            description="列出用户",
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "搜索查询"},
                    "page_size": {"type": "integer", "description": "每页数量"},
                    "page_token": {"type": "string", "description": "分页令牌"},
                },
            },
        ),
        Tool(
            name="auth.users.create",
            description="创建用户",
            inputSchema={
                "type": "object",
                "properties": {
                    "email": {"type": "string", "description": "用户邮箱"},
                    "password": {"type": "string", "description": "密码（可选）"},
                    "verified": {"type": "boolean", "description": "是否已验证"},
                },
                "required": ["email"],
            },
        ),
        Tool(
            name="auth.users.update",
            description="更新用户",
            inputSchema={
                "type": "object",
                "properties": {
                    "id_or_email": {"type": "string", "description": "用户 ID 或邮箱"},
                    "patch": {"type": "object", "description": "更新字段"},
                },
                "required": ["id_or_email", "patch"],
            },
        ),
        Tool(
            name="auth.users.delete",
            description="删除用户",
            inputSchema={
                "type": "object",
                "properties": {
                    "id_or_email": {"type": "string", "description": "用户 ID 或邮箱"},
                },
                "required": ["id_or_email"],
            },
        ),
        Tool(
            name="auth.sessions.invalidate",
            description="使会话失效",
            inputSchema={
                "type": "object",
                "properties": {
                    "id_or_email": {"type": "string", "description": "用户 ID 或邮箱"},
                },
                "required": ["id_or_email"],
            },
        ),
        Tool(
            name="auth.token.mint",
            description="生成认证令牌",
            inputSchema={
                "type": "object",
                "properties": {
                    "id_or_email": {"type": "string", "description": "用户 ID 或邮箱"},
                    "ttl_sec": {"type": "integer", "description": "令牌有效期（秒）"},
                },
                "required": ["id_or_email"],
            },
        ),
    ]


async def handle_auth_users_list(
    client: TrailBaseClient,
    query: str | None = None,
    page_size: int | None = None,
    page_token: str | None = None,
) -> list[TextContent]:
    """处理 auth.users.list 工具调用"""
    try:
        params: dict[str, Any] = {}
        if query:
            params["query"] = query
        if page_size:
            params["page_size"] = page_size
        if page_token:
            params["page_token"] = page_token

        result = client.http.get("/api/_admin/user", params=params)
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_auth_users_create(
    client: TrailBaseClient,
    email: str,
    password: str | None = None,
    verified: bool | None = None,
) -> list[TextContent]:
    """处理 auth.users.create 工具调用"""
    try:
        data: dict[str, Any] = {"email": email}
        if password:
            data["password"] = password
        if verified is not None:
            data["verified"] = verified

        result = client.http.post("/api/_admin/user", json=data)
        return [TextContent(type="text", text=json.dumps({"user": result}, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_auth_users_update(
    client: TrailBaseClient,
    id_or_email: str,
    patch: dict[str, Any],
) -> list[TextContent]:
    """处理 auth.users.update 工具调用"""
    try:
        result = client.http.patch(f"/api/_admin/user", json={**patch, "id_or_email": id_or_email})
        return [TextContent(type="text", text=json.dumps({"user": result}, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_auth_users_delete(
    client: TrailBaseClient,
    id_or_email: str,
) -> list[TextContent]:
    """处理 auth.users.delete 工具调用"""
    try:
        client.http.delete(f"/api/_admin/user", json={"id_or_email": id_or_email})
        return [TextContent(type="text", text=json.dumps({"ok": True}, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_auth_sessions_invalidate(
    client: TrailBaseClient,
    id_or_email: str,
) -> list[TextContent]:
    """处理 auth.sessions.invalidate 工具调用"""
    try:
        client.http.post(f"/api/_admin/user/{id_or_email}/sessions/invalidate")
        return [TextContent(type="text", text=json.dumps({"ok": True}, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_auth_token_mint(
    client: TrailBaseClient,
    id_or_email: str,
    ttl_sec: int | None = None,
) -> list[TextContent]:
    """处理 auth.token.mint 工具调用"""
    try:
        data: dict[str, Any] = {}
        if ttl_sec:
            data["ttl_sec"] = ttl_sec

        result = client.http.post(f"/api/_admin/user/{id_or_email}/tokens", json=data)
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]

