from typing import List, Optional

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

from apis.base import standard_response, StandardResponse, PageResponse, standard_error_response, convert_page_param
from db.database import get_db
from entity.device import Device, DeviceCreate, DeviceUpdate, DeviceInfo
from services.device_service import DeviceService

from app_instance import get_app

router = APIRouter()
app = get_app()

def get_service():
    return app.state.device_service


@router.get("/list", response_model=StandardResponse[List[DeviceInfo]])
async def get_device_list(
        name: Optional[str] = None,
        code: Optional[str] = None,
        device_type: Optional[str] = None,
        db: AsyncSession = Depends(get_db)):
    service = DeviceService(db)
    devices = await service.get_device_list(name, code, device_type)
    return standard_response(data=list(devices))


@router.get("/page/", response_model=StandardResponse[PageResponse[DeviceInfo]])
async def get_device_page(
        name: Optional[str] = None,
        code: Optional[str] = None,
        device_type: Optional[str] = None,
        offset: int = Query(0, ge=1),  # 从第几页开始
        limit: int = Query(10, ge=1),  # 每页显示多少条记录
        db: AsyncSession = Depends(get_db)):
    service = DeviceService(db)

    # 获取分页后的设备列表和总数
    offset, limit = convert_page_param(offset, limit)
    devices, total = await service.get_device_page(name, code, device_type, offset, limit)

    return standard_response(
        data=PageResponse(total=total, items=devices)
    )


@router.post("/add", response_model=StandardResponse[DeviceInfo])
async def create_device(device_data: DeviceCreate, service: DeviceService = Depends(get_service)):
    device = await service.create_device(device_data)
    return standard_response(data=device)


@router.post("/update", response_model=StandardResponse[DeviceInfo])
async def update_device(device_data: DeviceUpdate, service: DeviceService = Depends(get_service)):
    device = await service.update_device(device_data)
    if not device:
        return standard_error_response(data=device_data, message="Device not found")
    return standard_response(data=device)


@router.delete("/delete", response_model=StandardResponse[int])
async def delete_device(device_id: int, service: DeviceService = Depends(get_service)):
    device = await service.delete_device(device_id)
    if not device:
        return standard_error_response(data=device_id, message="Device not found")
    return standard_response(data=device_id)
