"""Game management router endpoints."""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, insert, update, delete
from typing import Optional, List
from datetime import datetime

from app.core.database import get_db
from app.core.security import get_current_user
from app.models.models import User
from app.schemas.schemas import GameCreate, GameResponse

router = APIRouter()


@router.get("/", response_model=List[GameResponse])
async def list_games(
    room_id: Optional[int] = None,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """List active games."""
    # This would query a games table - simplified for now
    # In production, you'd have a MTG OnlineGames model
    return []


@router.post("/", response_model=GameResponse)
async def create_game(
    request: GameCreate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """Create a new game."""
    user_id = int(current_user["user_id"])
    
    # Verify user exists
    stmt = select(User).where(User.id == user_id)
    result = await db.execute(stmt)
    user = result.scalar_one_or_none()
    
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found",
        )
    
    # In production, you'd create a game in the game database
    # For now, return a mock response
    game_data = {
        "id": 1,  # Mock ID
        "room_id": request.room_id,
        "game_type": request.game_type,
        "description": request.description,
        "with_password": bool(request.password),
        "max_players": 4,
        "player_count": 1,
        "started": False,
        "creation_date": datetime.now(),
    }
    
    return GameResponse(**game_data)


@router.get("/{game_id}", response_model=GameResponse)
async def get_game(
    game_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """Get game by ID."""
    # In production, query the games table
    return GameResponse(
        id=game_id,
        room_id=1,
        game_type="Casual",
        description="Test game",
        with_password=False,
        max_players=4,
        player_count=0,
        started=False,
        creation_date=datetime.now(),
    )


@router.post("/{game_id}/join")
async def join_game(
    game_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """Join a game."""
    user_id = int(current_user["user_id"])
    
    # In production, add user to game players table
    return {"message": f"User {user_id} joined game {game_id}"}


@router.post("/{game_id}/leave")
async def leave_game(
    game_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """Leave a game."""
    user_id = int(current_user["user_id"])
    
    # In production, remove user from game players table
    return {"message": f"User {user_id} left game {game_id}"}


@router.post("/{game_id}/start")
async def start_game(
    game_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """Start a game (host only)."""
    user_id = int(current_user["user_id"])
    
    # In production, update game started status
    return {"message": f"Game {game_id} started"}


@router.post("/{game_id}/end")
async def end_game(
    game_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """End a game."""
    user_id = int(current_user["user_id"])
    
    # In production, update game closed status
    return {"message": f"Game {game_id} ended"}
