"""Tests for RBAC access_service: client access by role and team membership."""
import uuid

import pytest

from services.access_service import get_accessible_client_ids, get_accessible_clients


class TestSuperAdminAccess:
    async def test_super_admin_sees_all_active_clients(
        self, session, make_user, make_client
    ):
        admin = await make_user(email="admin@test.com", role="super_admin")
        c1 = await make_client(name="Client A", slug="client-a")
        c2 = await make_client(name="Client B", slug="client-b")
        # Inactive client should be excluded
        await make_client(name="Inactive", slug="inactive", is_active=False)

        ids = await get_accessible_client_ids(admin, session)
        assert set(ids) == {c1.id, c2.id}

    async def test_super_admin_gets_full_client_objects(
        self, session, make_user, make_client
    ):
        admin = await make_user(email="admin@test.com", role="super_admin")
        await make_client(name="X Corp", slug="x-corp")

        clients = await get_accessible_clients(admin, session)
        assert len(clients) == 1
        assert clients[0].name == "X Corp"


class TestRegularUserAccess:
    async def test_user_sees_only_team_linked_clients(
        self, session, make_user, make_client, make_team, make_membership
    ):
        user = await make_user(email="user@test.com", role="user")
        c1 = await make_client(name="My Client", slug="my-client")
        c2 = await make_client(name="Other Client", slug="other-client")

        team = await make_team(name="Team A", client_id=c1.id)
        await make_membership(user_id=user.id, team_id=team.id)

        ids = await get_accessible_client_ids(user, session)
        assert c1.id in ids
        assert c2.id not in ids

    async def test_user_with_no_teams_sees_nothing(
        self, session, make_user, make_client
    ):
        user = await make_user(email="lonely@test.com", role="user")
        await make_client(name="Some Corp", slug="some-corp")

        ids = await get_accessible_client_ids(user, session)
        assert ids == []

        clients = await get_accessible_clients(user, session)
        assert clients == []

    async def test_user_sees_multiple_clients_via_multiple_teams(
        self, session, make_user, make_client, make_team, make_membership
    ):
        user = await make_user(email="multi@test.com", role="user")
        c1 = await make_client(name="Client 1", slug="client-1")
        c2 = await make_client(name="Client 2", slug="client-2")

        t1 = await make_team(name="Team 1", client_id=c1.id)
        t2 = await make_team(name="Team 2", client_id=c2.id)
        await make_membership(user_id=user.id, team_id=t1.id)
        await make_membership(user_id=user.id, team_id=t2.id)

        ids = await get_accessible_client_ids(user, session)
        assert set(ids) == {c1.id, c2.id}
