from template_project.application.common.data_structure import to_data_structure
from template_project.application.common.identity_provider import IdentityProvider
from template_project.application.common.interactor import to_interactor
from template_project.application.common.unit_of_work import UnitOfWork
from template_project.application.notification_device.data_gateway import NotificationDeviceDataGateway
from template_project.application.notification_device.entity import NotificationDevice


@to_data_structure
class RegisterNotificationDeviceRequest:
    device_id: str


@to_interactor
class RegisterNotificationDeviceInteractor:
    identity_provider: IdentityProvider
    notification_device_data_gateway: NotificationDeviceDataGateway
    unit_of_work: UnitOfWork

    async def execute(self, request: RegisterNotificationDeviceRequest) -> None:
        current_user = await self.identity_provider.get_current_user()

        existing_device = await self.notification_device_data_gateway.load_by_user_id_and_device_id(
            user_id=current_user.id,
            device_id=request.device_id,
        )

        if existing_device:
            return

        notification_device = NotificationDevice.factory(
            user_id=current_user.id,
            device_id=request.device_id,
        )

        await self.unit_of_work.add(notification_device)
        await self.unit_of_work.commit()
