"""分页参数和返回结构。"""

from __future__ import annotations

from dataclasses import dataclass
from math import ceil
from typing import Any

from dms.common.errors import InvalidArgumentError


DEFAULT_PAGE = 1
DEFAULT_PAGE_SIZE = 20
MAX_PAGE_SIZE = 100


@dataclass(frozen=True, slots=True)
class PageRequest:
    page: int = DEFAULT_PAGE
    page_size: int = DEFAULT_PAGE_SIZE

    def __post_init__(self) -> None:
        if self.page < 1:
            raise InvalidArgumentError("page必须大于等于1")
        if self.page_size < 1 or self.page_size > MAX_PAGE_SIZE:
            raise InvalidArgumentError("pageSize必须在1到100之间")

    @property
    def offset(self) -> int:
        return (self.page - 1) * self.page_size


def page_result(
    items: list[Any],
    *,
    page: int,
    page_size: int,
    total: int,
) -> dict[str, Any]:
    return {
        "items": items,
        "page": page,
        "pageSize": page_size,
        "total": total,
        "totalPages": ceil(total / page_size) if total else 0,
    }
