from __future__ import annotations
import secrets
from chitai.database.models.kosync_device import KosyncDevice
from advanced_alchemy.service import (
    SQLAlchemyAsyncRepositoryService,
    ModelDictT,
    schema_dump,
)
from advanced_alchemy.repository import SQLAlchemyAsyncRepository


class KosyncDeviceService(SQLAlchemyAsyncRepositoryService[KosyncDevice]):
    """Service for managing KOReader devices."""

    API_KEY_LENGTH_IN_BYTES = 8

    class Repo(SQLAlchemyAsyncRepository[KosyncDevice]):
        """Repository for KosyncDevice entities."""

        model_type = KosyncDevice

    repository_type = Repo

    async def create(self, data: ModelDictT[KosyncDevice], **kwargs) -> KosyncDevice:
        data = schema_dump(data)
        data["api_key"] = self._generate_api_key()
        return await super().create(data, **kwargs)

    async def get_by_api_key(self, api_key: str) -> KosyncDevice:
        return await self.get_one(KosyncDevice.api_key == api_key)

    async def regenerate_api_key(self, device_id: int) -> KosyncDevice:
        device = await self.get(device_id)
        api_key = self._generate_api_key()
        device.api_key = api_key
        return await self.update(device)

    def _generate_api_key(self) -> str:
        return secrets.token_hex(self.API_KEY_LENGTH_IN_BYTES)
