"""Internal /v1 personal access token management."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from ...models.v1.jobs import WriteResult
from ...models.v1.keys import ApiKeyPublic, ApiKeyWithSecret, RotateKeyResponse
from ...models.v1.pagination import Page, Pagination

if TYPE_CHECKING:
    from ..._http import HttpTransport


class KeysResource:
    """client.keys — self-managed PAT list, create, update, revoke, rotate."""

    def __init__(self, http: HttpTransport) -> None:
        self._http = http

    def list(
        self,
        *,
        include_revoked: bool = False,
        key_type: str | None = None,
        page_size: int = 50,
        cursor: str | None = None,
    ) -> Page[ApiKeyPublic]:
        params: dict[str, Any] = {"page_size": page_size, "include_revoked": include_revoked}
        if cursor is not None:
            params["cursor"] = cursor
        if key_type is not None:
            params["key_type"] = key_type

        data = self._http.get("/auth/keys", params=params)
        items = [ApiKeyPublic.model_validate(i) for i in data.get("data", [])]
        pagination = Pagination.model_validate(data.get("pagination", {}) or {})
        return Page[ApiKeyPublic](
            data=items, pagination=pagination, request_id=data.get("request_id")
        )

    def get(self, key_id: str) -> ApiKeyPublic:
        data = self._http.get(f"/auth/keys/{key_id}")
        return ApiKeyPublic.model_validate(data.get("data", {}))

    def create(
        self,
        name: str,
        *,
        scopes: list[str] | None = None,
        description: str | None = None,
        rate_limit_rpm: int | None = None,
    ) -> ApiKeyWithSecret:
        payload: dict[str, Any] = {"name": name}
        if scopes is not None:
            payload["scopes"] = scopes
        if description is not None:
            payload["description"] = description
        if rate_limit_rpm is not None:
            payload["rate_limit_rpm"] = rate_limit_rpm
        data = self._http.post("/auth/keys", json=payload)
        return ApiKeyWithSecret.model_validate(data.get("data", {}))

    def update(
        self,
        key_id: str,
        *,
        scopes: list[str] | None = None,
    ) -> ApiKeyPublic:
        payload: dict[str, Any] = {}
        if scopes is not None:
            payload["scopes"] = scopes
        data = self._http.patch(f"/auth/keys/{key_id}", json=payload)
        return ApiKeyPublic.model_validate(data.get("data", {}))

    def revoke(self, key_id: str, reason: str | None = None) -> WriteResult:
        payload = {"reason": reason} if reason is not None else None
        data = self._http.delete(f"/auth/keys/{key_id}", json=payload)
        return WriteResult.model_validate(data)

    def rotate(self, key_id: str) -> RotateKeyResponse:
        data = self._http.post(f"/auth/keys/{key_id}/rotate", json={})
        return RotateKeyResponse.model_validate(data.get("data", {}))

    def iter(
        self, *, include_revoked: bool = False, key_type: str | None = None, page_size: int = 50
    ):
        from ...models.v1.pagination import auto_paginate

        return auto_paginate(
            self.list, include_revoked=include_revoked, key_type=key_type, page_size=page_size
        )
