#  Copyright (C) 2025
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Aleksandr Medvedev <a.medvedev@abm-jsc.ru>

from dataclasses import dataclass

from http_tools import AbmServiceConnector
from typeful import to_dataclass


@dataclass(frozen=True, slots=True)
class Scopes:
    course_ids: tuple[int, ...] | None = None
    community_ids: tuple[int, ...] | None = None


@dataclass(frozen=True, slots=True)
class TeamMemberRole:
    id: int
    title: str
    action_codes: frozenset[str]
    scopes: Scopes


@dataclass(frozen=True, slots=True)
class TeamMemberAccess:
    portal_member_id: int
    team_member_role: TeamMemberRole


@dataclass(frozen=True, slots=True)
class PortalMember:
    id: int
    first_name: str
    last_name: str
    email: str
    avatar_id: str | None = None


@dataclass(frozen=True, slots=True)
class TeamMember:
    id: int
    portal_id: int
    team_member_role_id: int
    invited_email: str
    invited_code: str
    invited_at: int
    last_email_sent_at: int
    activated_at: int | None = None
    enabled_at: int | None = None
    portal_member: PortalMember | None = None


class TeamMemberServerConnector:
    Config = AbmServiceConnector.Config

    @dataclass(slots=True)
    class Context(AbmServiceConnector.Context):
        server_name: str

    def __init__(self, config: Config, context: Context) -> None:
        self._context = context
        self._http_connector = AbmServiceConnector(config, context)

    # TODO: may be need to add cache
    async def get_team_member_access(self, portal_member_id: int) -> TeamMemberAccess:
        answer = await self._http_connector.post(
            "/v1/team_member/access/get",
            payload={"portal_member_id": portal_member_id},
            headers={"server_name": self._context.server_name},
        )
        return to_dataclass(answer, TeamMemberAccess)

    async def get_team_members(self, portal_id: int) -> list[TeamMember]:
        answer = await self._http_connector.post(
            "/v1/team_member/list",
            payload={"portal_id": portal_id},
            headers={"server_name": self._context.server_name},
        )
        return [to_dataclass(tm, TeamMember) for tm in answer]
