"""Public /v1 workers."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from ...models.v1.common import WriteResult
from ...models.v1.pagination import Page
from ...models.v1.workers import (
    BatchUpsertWorkersRequest,
    CreateWorkerRequest,
    UpdateWorkerRequest,
    WorkerDetail,
    WorkerSummary,
)
from ._helpers import dump_model, parse_detail, parse_page

if TYPE_CHECKING:
    from ..._http import HttpTransport


class WorkersResource:
    """client.workers — /v1/workers."""

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

    def list(
        self,
        *,
        collection_id: str | None = None,
        partner_id: str | None = None,
        factory_id: str | None = None,
        page_size: int = 50,
        cursor: str | None = None,
    ) -> Page[WorkerSummary]:
        params: dict[str, Any] = {"page_size": page_size}
        for key, value in {
            "cursor": cursor,
            "collection_id": collection_id,
            "partner_id": partner_id,
            "factory_id": factory_id,
        }.items():
            if value is not None:
                params[key] = value

        return parse_page(self._http.get("/workers", params=params), WorkerSummary)

    def get(self, worker_id: str) -> WorkerDetail:
        return parse_detail(self._http.get(f"/workers/{worker_id}"), WorkerDetail)

    def create(self, body: CreateWorkerRequest) -> WorkerDetail:
        return parse_detail(
            self._http.post("/workers", json=dump_model(body)),
            WorkerDetail,
        )

    def batch(self, body: BatchUpsertWorkersRequest) -> WriteResult:
        return parse_detail(
            self._http.post("/workers/batch", json=dump_model(body)),
            WriteResult,
        )

    def update(self, worker_id: str, body: UpdateWorkerRequest) -> WorkerDetail:
        return parse_detail(
            self._http.patch(f"/workers/{worker_id}", json=dump_model(body)),
            WorkerDetail,
        )
