# -*- coding: utf-8 -*-
from __future__ import annotations

import logging

from social_core.backends.open_id_connect import OpenIdConnectAuth

LOGGER = logging.getLogger(__name__)


class HotPocketOpenIdConnectAuth(OpenIdConnectAuth):
    name = 'hotpocket_oidc'


def _get_roles_from_response(response) -> list[str]:
    from hotpocket_backend.apps.core.conf import settings
    return response.\
        get('resource_access', {}).\
        get(settings.SECRETS.OIDC.key, {}).\
        get('roles', [])


def set_user_is_staff(strategy, details, response, user=None, *args, **kwargs):
    if user is None:
        return None

    roles = _get_roles_from_response(response)
    user.is_staff = 'staff' in roles

    strategy.storage.user.changed(user)


def set_user_is_superuser(strategy, details, response, user=None, *args, **kwargs):
    if user is None:
        return None

    roles = _get_roles_from_response(response)
    user.is_superuser = 'superuser' in roles

    strategy.storage.user.changed(user)
