"""Database Migrations resource."""

from __future__ import annotations

import builtins

from .._client import AplikuClient
from .._models import LogEntry, Migration, MigrationRun, PaginatedResponse

_list = builtins.list


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

    def _base(self, team: str) -> str:
        return f"/api/team/{team}/database_migrations"

    def list(
        self, team: str, *, page: int = 1, page_size: int = 20
    ) -> PaginatedResponse[Migration]:
        """List migrations for a team."""
        return self._client.paginate(
            f"{self._base(team)}/run",
            params={"page": page, "page_size": page_size},
            response_type=Migration,
        )

    def get(self, team: str, migration_id: int) -> Migration:
        """Get a single migration."""
        data = self._client.get(f"{self._base(team)}/{migration_id}")
        return Migration.model_validate(data)

    def run(self, team: str, application_id: int, command: str) -> Migration:
        """Run a database migration."""
        body = MigrationRun(application_id=application_id, command=command)
        data = self._client.post(f"{self._base(team)}/run", json=body.model_dump())
        return Migration.model_validate(data)

    def logs(self, team: str, migration_id: int) -> _list[LogEntry]:
        """Get migration logs."""
        data = self._client.get(f"{self._base(team)}/{migration_id}/logs")
        results = data if isinstance(data, builtins.list) else data.get("results", [])
        return [LogEntry.model_validate(entry) for entry in results]
