"""Public /v1 factories."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from ...models.v1.common import WriteResult
from ...models.v1.factories import (
    BatchUpsertFactoriesRequest,
    CreateFactoryRequest,
    FactoryDetail,
    FactorySummary,
    UpdateFactoryRequest,
)
from ...models.v1.pagination import Page
from ._helpers import dump_model, parse_detail, parse_page

if TYPE_CHECKING:
    from ..._http import HttpTransport


class FactoriesResource:
    """client.factories — /v1/factories."""

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

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

        return parse_page(self._http.get("/factories", params=params), FactorySummary)

    def get(self, factory_id: str) -> FactoryDetail:
        return parse_detail(self._http.get(f"/factories/{factory_id}"), FactoryDetail)

    def create(self, body: CreateFactoryRequest) -> FactoryDetail:
        return parse_detail(
            self._http.post("/factories", json=dump_model(body)),
            FactoryDetail,
        )

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

    def update(self, factory_id: str, body: UpdateFactoryRequest) -> FactoryDetail:
        return parse_detail(
            self._http.patch(f"/factories/{factory_id}", json=dump_model(body)),
            FactoryDetail,
        )
