"""CronJobs resource."""

from __future__ import annotations

from .._client import AplikuClient
from .._models import CronJob, CronJobCreate, CronJobUpdate, PaginatedResponse


class CronJobsResource:
    def __init__(self, client: AplikuClient) -> None:
        self._client = client

    def _base(self, team: str, app_id: int) -> str:
        return f"/api/team/{team}/applications/{app_id}/cron_jobs"

    def list(
        self, team: str, app_id: int, *, page: int = 1, page_size: int = 20
    ) -> PaginatedResponse[CronJob]:
        """List cron jobs for an app."""
        return self._client.paginate(
            f"{self._base(team, app_id)}/",
            params={"page": page, "page_size": page_size},
            response_type=CronJob,
        )

    def get(self, team: str, app_id: int, cron_id: int) -> CronJob:
        """Get a single cron job."""
        data = self._client.get(f"{self._base(team, app_id)}/{cron_id}/")
        return CronJob.model_validate(data)

    def create(self, team: str, app_id: int, name: str, schedule: str, command: str) -> CronJob:
        """Create a cron job."""
        body = CronJobCreate(name=name, schedule=schedule, command=command)
        data = self._client.post(
            f"{self._base(team, app_id)}/",
            json=body.model_dump(),
        )
        return CronJob.model_validate(data)

    def update(self, team: str, app_id: int, cron_id: int, **kwargs: object) -> CronJob:
        """Partially update a cron job."""
        body = CronJobUpdate(**kwargs)  # type: ignore[arg-type]
        data = self._client.patch(
            f"{self._base(team, app_id)}/{cron_id}/",
            json=body.model_dump(exclude_none=True),
        )
        return CronJob.model_validate(data)

    def delete(self, team: str, app_id: int, cron_id: int) -> None:
        """Delete a cron job."""
        self._client.delete(f"{self._base(team, app_id)}/{cron_id}/")
