from __future__ import annotations from datetime import datetime, timezone from core.dal.base_repository import BaseRepository class ServerRepository(BaseRepository): def get_all(self, game_type: str | None = None) -> list[dict]: if game_type: return self._fetchall( "SELECT * FROM servers WHERE game_type = :gt ORDER BY name", {"gt": game_type}, ) return self._fetchall("SELECT * FROM servers ORDER BY name") def get_by_id(self, server_id: int) -> dict | None: return self._fetchone("SELECT * FROM servers WHERE id = :id", {"id": server_id}) def create( self, name: str, game_type: str, exe_path: str, game_port: int, rcon_port: int | None = None, description: str | None = None, auto_restart: bool = False, max_restarts: int = 3, ) -> int: return self._lastrowid( """ INSERT INTO servers (name, description, game_type, exe_path, game_port, rcon_port, auto_restart, max_restarts) VALUES (:name, :desc, :game_type, :exe, :gp, :rp, :ar, :mr) """, { "name": name, "desc": description, "game_type": game_type, "exe": exe_path, "gp": game_port, "rp": rcon_port, "ar": int(auto_restart), "mr": max_restarts, }, ) def update(self, server_id: int, **fields) -> None: if not fields: return fields["updated_at"] = datetime.now(timezone.utc).isoformat() fields["id"] = server_id set_clause = ", ".join(f"{k} = :{k}" for k in fields if k != "id") self._execute(f"UPDATE servers SET {set_clause} WHERE id = :id", fields) def update_status( self, server_id: int, status: str, pid: int | None = None, started_at: str | None = None, stopped_at: str | None = None, ) -> None: now = datetime.now(timezone.utc).isoformat() self._execute( """ UPDATE servers SET status = :status, pid = :pid, started_at = :sa, stopped_at = :sta, updated_at = :now WHERE id = :id """, { "status": status, "pid": pid, "sa": started_at, "sta": stopped_at, "now": now, "id": server_id, }, ) def delete(self, server_id: int) -> None: self._execute("DELETE FROM servers WHERE id = :id", {"id": server_id}) def get_running(self) -> list[dict]: return self._fetchall( "SELECT * FROM servers WHERE status IN ('running', 'starting')" ) def increment_restart_count(self, server_id: int) -> None: now = datetime.now(timezone.utc).isoformat() self._execute( """ UPDATE servers SET restart_count = restart_count + 1, last_restart_at = :now, updated_at = :now WHERE id = :id """, {"now": now, "id": server_id}, ) def reset_restart_count(self, server_id: int) -> None: self._execute( "UPDATE servers SET restart_count = 0 WHERE id = :id", {"id": server_id}, )