from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.deps import require_role
from app.database import get_db
from app.models.user import User
from app.schemas.cloud_server import (
    CloudServerCreate,
    CloudServerResponse,
    CloudServerTestRequest,
    CloudServerUpdate,
)
from app.schemas.common import ApiResponse
from app.services import cloud_server_service

router = APIRouter()

_admin = require_role("admin", "super_admin")


@router.get("", response_model=ApiResponse)
async def list_servers(
    db: AsyncSession = Depends(get_db),
    _: User = Depends(_admin),
):
    servers = await cloud_server_service.list_servers(db)
    return ApiResponse(data=[CloudServerResponse.model_validate(s) for s in servers])


@router.post("", response_model=ApiResponse)
async def create_server(
    data: CloudServerCreate,
    db: AsyncSession = Depends(get_db),
    _: User = Depends(_admin),
):
    server = await cloud_server_service.create_server(db, data)
    return ApiResponse(data=CloudServerResponse.model_validate(server))


@router.get("/{server_id}", response_model=ApiResponse)
async def get_server(
    server_id: int,
    db: AsyncSession = Depends(get_db),
    _: User = Depends(_admin),
):
    server = await cloud_server_service.get_server(db, server_id)
    return ApiResponse(data=CloudServerResponse.model_validate(server))


@router.put("/{server_id}", response_model=ApiResponse)
async def update_server(
    server_id: int,
    data: CloudServerUpdate,
    db: AsyncSession = Depends(get_db),
    _: User = Depends(_admin),
):
    server = await cloud_server_service.update_server(db, server_id, data)
    return ApiResponse(data=CloudServerResponse.model_validate(server))


@router.delete("/{server_id}", response_model=ApiResponse)
async def delete_server(
    server_id: int,
    db: AsyncSession = Depends(get_db),
    _: User = Depends(_admin),
):
    await cloud_server_service.delete_server(db, server_id)
    return ApiResponse(data=None)


@router.post("/{server_id}/test", response_model=ApiResponse)
async def test_saved(
    server_id: int,
    db: AsyncSession = Depends(get_db),
    _: User = Depends(_admin),
):
    result = await cloud_server_service.test_saved_server(db, server_id)
    return ApiResponse(data=result)


@router.post("/test", response_model=ApiResponse)
async def test_unsaved(
    data: CloudServerTestRequest,
    _: User = Depends(_admin),
):
    result = await cloud_server_service.test_unsaved(data)
    return ApiResponse(data=result)
