from advanced_alchemy.service.pagination import OffsetPagination

from chitai.database.models.kosync_device import KosyncDevice
from chitai.database.models.user import User
from chitai.schemas.kosync import KosyncDeviceCreate, KosyncDeviceRead
from chitai.services.kosync_device import KosyncDeviceService
from litestar import Controller, post, get, delete
from litestar.di import Provide
from chitai.services import dependencies as deps


class DeviceController(Controller):
    """Controller for managing KOReader devices."""

    dependencies = {"device_service": Provide(deps.provide_kosync_device_service)}

    path = "/devices"

    @get()
    async def get_devices(
        self, device_service: KosyncDeviceService, current_user: User
    ) -> OffsetPagination[KosyncDeviceRead]:
        """Return a list of all the user's devices."""
        devices = await device_service.list(KosyncDevice.user_id == current_user.id)
        return device_service.to_schema(devices, schema_type=KosyncDeviceRead)

    @post()
    async def create_device(
        self,
        data: KosyncDeviceCreate,
        device_service: KosyncDeviceService,
        current_user: User,
    ) -> KosyncDeviceRead:
        device = await device_service.create(
            {"name": data.name, "user_id": current_user.id}
        )
        return device_service.to_schema(device, schema_type=KosyncDeviceRead)

    @delete("/{device_id:int}")
    async def delete_device(
        self, device_id: int, device_service: KosyncDeviceService, current_user: User
    ) -> None:
        # Ensure the device exists and is owned by the user
        device = await device_service.get_one(
            KosyncDevice.id == device_id, KosyncDevice.user_id == current_user.id
        )
        await device_service.delete(device.id)

    @get("/{device_id:int}/regenerate")
    async def regenerate_device_api_key(
        self, device_id: int, device_service: KosyncDeviceService, current_user: User
    ) -> KosyncDeviceRead:
        # Ensure the device exists and is owned by the user
        device = await device_service.get_one(
            KosyncDevice.id == device_id, KosyncDevice.user_id == current_user.id
        )
        updated_device = await device_service.regenerate_api_key(device.id)
        return device_service.to_schema(updated_device, schema_type=KosyncDeviceRead)
