"""Fleet driver online/offline presence helpers."""

from __future__ import annotations

from django.utils import timezone

from accounts.models import TransporterProfile


def get_driver_is_online(user) -> bool:
    if not user:
        return False
    profile = getattr(user, 'transporter_profile', None)
    if profile is None:
        return False
    return bool(getattr(profile, 'is_online', False))


def get_driver_online_updated_at(user):
    if not user:
        return None
    profile = getattr(user, 'transporter_profile', None)
    if profile is None:
        return None
    value = getattr(profile, 'online_updated_at', None)
    return value.isoformat() if value else None


def driver_presence_fields(user) -> dict:
    return {
        'is_online': get_driver_is_online(user),
        'online_updated_at': get_driver_online_updated_at(user),
    }


def set_driver_online(user, *, is_online: bool) -> TransporterProfile:
    profile = user.transporter_profile
    profile.is_online = bool(is_online)
    profile.online_updated_at = timezone.now()
    profile.save(update_fields=['is_online', 'online_updated_at', 'updated_at'])
    return profile


def driver_presence_payload(user) -> dict:
    profile = getattr(user, 'transporter_profile', None)
    return {
        'user_id': user.id,
        'account_type': getattr(profile, 'account_type', None),
        **driver_presence_fields(user),
    }
