class Games:
    def __init__(self, client):
        self.client = client

    def list(self, page=None, per_page=None, search=None, author=None):
        params = {}
        if page is not None:
            params['page'] = page
        if per_page is not None:
            params['per_page'] = per_page
        if search is not None:
            params['search'] = search
        if author is not None:
            params['author'] = author
        return self.client._get("/games/", params=params)

    def list_all(self):
        """Получить ВСЕ игры (автопагинация)"""
        all_games = []
        page = 1
        while True:
            data = self.list(page=page, per_page=100)
            games = data.get('games', [])
            all_games.extend(games)
            pagination = data.get('pagination', {})
            if not pagination.get('has_next', False):
                break
            page += 1
        return {'games': all_games, 'total': len(all_games)}

    def get(self, game_id):
        return self.client._get(f"/games/{game_id}")

    def create(self, **data):
        return self.client._post("/games/", data)

    def update(self, game_id, **data):
        return self.client._put(f"/games/{game_id}", data)

    def delete(self, game_id):
        return self.client._delete(f"/games/{game_id}")

    def add_platform(self, game_id, platform_id, price=None, keys=None, is_available=True):
        data = {"platform_id": platform_id}
        if price is not None:
            data["price"] = price
        if keys is not None:
            data["keys"] = keys
        data["is_available"] = is_available
        return self.client._post(f"/games/{game_id}/platforms", data)

    def update_platform(self, game_platform_id, **data):
        return self.client._put(f"/games/platforms/{game_platform_id}", data)

    def remove_platform(self, game_platform_id):
        return self.client._delete(f"/games/platforms/{game_platform_id}")

    def get_keys(self, game_platform_id):
        return self.client._get(f"/games/platforms/{game_platform_id}/keys")

    def add_keys(self, game_platform_id, keys=None, count=None):
        data = {}
        if keys is not None:
            data["keys"] = keys
        if count is not None:
            data["count"] = count
        return self.client._post(f"/games/platforms/{game_platform_id}/keys", data)

    def delete_key(self, key_id):
        return self.client._delete(f"/games/keys/{key_id}")

    def grant_to_player(self, player_id, game_id, platform_id):
        data = {
            "player_id": player_id,
            "game_id": game_id,
            "platform_id": platform_id
        }
        return self.client._post("/games/grant", data)