from channels.db import database_sync_to_async
from channels.generic.websocket import AsyncJsonWebsocketConsumer

from apps.accounts_rbac.models import CompanyMembership


class NotificationWebsocketConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        user = self.scope.get("user")
        if not user or not user.is_authenticated or not user.is_active:
            await self.close(code=4401)
            return

        self.user = user
        self.user_group = f"notif_user_{user.id}"
        has_company = await self._has_active_membership(user)
        if not has_company:
            await self.close(code=4403)
            return

        if await self._is_device_revoked(user):
            await self.close(code=4401)
            return

        await self.channel_layer.group_add(self.user_group, self.channel_name)
        await self.accept()
        await self._track_ws_count(1)
        await self.send_json({"type": "connected", "user_id": str(user.id)})

    async def disconnect(self, close_code):
        if hasattr(self, "user_group"):
            await self.channel_layer.group_discard(self.user_group, self.channel_name)
            await self._track_ws_count(-1)

    async def receive_json(self, content, **kwargs):
        if content.get("type") == "ping":
            await self.send_json({"type": "pong"})

    async def notification_event(self, event):
        await self.send_json(event["payload"])

    async def force_disconnect(self, event):
        await self.send_json({"type": "session_revoked", "detail": event.get("reason", "Session revoked")})
        await self.close(code=4401)

    @database_sync_to_async
    def _has_active_membership(self, user) -> bool:
        if user.is_superuser:
            return True
        return CompanyMembership.objects.filter(user=user, is_active=True).exists()

    @database_sync_to_async
    def _is_device_revoked(self, user) -> bool:
        from apps.accounts_rbac.models import Device

        hdrs = dict(self.scope.get("headers") or [])
        dev_id = (hdrs.get(b"x-device-id") or b"").decode("utf-8", errors="ignore").strip()
        if not dev_id:
            return False
        return Device.objects.filter(user=user, device_id=dev_id, status=Device.Status.REVOKED).exists()

    @database_sync_to_async
    def _track_ws_count(self, delta: int) -> None:
        from django.core.cache import cache

        try:
            curr = int(cache.get("maya:ws:active_connections") or 0)
            cache.set("maya:ws:active_connections", max(0, curr + delta), timeout=3600)
        except Exception:
            pass

