import logging

from ..registry import registry

logger = logging.getLogger("django_devicehub.auth")


class DeviceAuthBackend:
    """Authenticate devices by MQTT username/password or API key.

    Searches across all registered device models to find a match.
    """

    @staticmethod
    def authenticate(username, password):
        """Check MQTT credentials against all registered device models.

        Returns the device instance if authenticated, None otherwise.
        """
        for dt_cls, device_model, _, _ in registry.all_with_models():
            try:
                device = device_model.objects.get(
                    mqtt_username=username,
                    is_active=True,
                )
                if device.check_mqtt_password(password):
                    logger.info("Device authenticated: %s", device.device_id)
                    return device
                else:
                    logger.warning("Bad password for device: %s", username)
                    return None
            except device_model.DoesNotExist:
                continue

        logger.warning("Unknown device username: %s", username)
        return None

    @staticmethod
    def authenticate_api_key(api_key):
        """Authenticate a device by API key.

        Returns the device instance if found, None otherwise.
        """
        for dt_cls, device_model, _, _ in registry.all_with_models():
            try:
                device = device_model.objects.get(
                    api_key=api_key,
                    is_active=True,
                )
                return device
            except device_model.DoesNotExist:
                continue
        return None
