"""JWT token creation utility.

JWT 令牌生成工具模块。
提供统一的令牌创建函数，供 SSO 认证和 Mock 测试端点复用。
"""

from __future__ import annotations

from datetime import datetime, timedelta, timezone

from jose import jwt
from pydantic import BaseModel, Field

from app.config import settings


class TokenClaims(BaseModel):
    """Input claims for token generation.

    令牌生成的输入参数，包含用户身份信息。
    """

    user_id: str
    user_name: str = ""
    office_id: str = ""
    office_name: str = ""
    dept_id: str = ""
    dept_name: str = ""
    area_id: str = ""
    area_name: str = ""
    role_ids: list[str] = Field(default_factory=list)


class TokenResult(BaseModel):
    """Output of token generation.

    令牌生成的输出，包含签名后的 JWT 和过期时间。
    """

    access_token: str
    expires_in: int  # seconds


def create_access_token(
    claims: TokenClaims,
    *,
    expires_minutes: int = 1440,
    issuer: str = "zm-rag",
) -> TokenResult:
    """Create a signed JWT from the given claims.

    根据用户身份信息创建签名的 JWT 令牌。

    Args:
        claims: User identity claims to embed in the token.
        expires_minutes: Token lifetime in minutes (default 24 hours).
        issuer: Value for the ``iss`` claim.

    Returns:
        TokenResult with the encoded JWT and expiration in seconds.
    """
    now = datetime.now(tz=timezone.utc)
    expire = now + timedelta(minutes=expires_minutes)

    payload = {
        "sub": claims.user_id,
        "user_name": claims.user_name,
        "office_id": claims.office_id,
        "office_name": claims.office_name,
        "dept_id": claims.dept_id,
        "dept_name": claims.dept_name,
        "area_id": claims.area_id,
        "area_name": claims.area_name,
        "role_ids": claims.role_ids,
        "iat": int(now.timestamp()),
        "exp": int(expire.timestamp()),
        "iss": issuer,
    }

    token = jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)

    return TokenResult(
        access_token=token,
        expires_in=expires_minutes * 60,
    )
