import pytest
from cloud.teams.team_store import TeamStore

@pytest.fixture
def store(tmp_path):
    return TeamStore(tmp_path)

def test_create_and_get_team(store):
    team_id = store.create_team("Test Team", "user_1")
    team = store.get_team(team_id)
    assert team is not None
    assert team["name"] == "Test Team"
    assert team["owner"] == "user_1"
    assert len(team["members"]) == 1
    assert team["members"][0]["user_id"] == "user_1"
    assert team["members"][0]["role"] == "admin"

def test_invite_member(store):
    team_id = store.create_team("Test Team", "user_1")
    assert store.invite_member(team_id, "user_2", "member") == True
    assert store.team_size(team_id) == 2
    assert store.get_member_role(team_id, "user_2") == "member"
    
    # duplicate invite
    assert store.invite_member(team_id, "user_2") == False

def test_remove_member(store):
    team_id = store.create_team("Test Team", "user_1")
    store.invite_member(team_id, "user_2", "member")
    
    assert store.remove_member(team_id, "user_2") == True
    assert store.team_size(team_id) == 1
    assert store.remove_member(team_id, "user_not_exist") == False

def test_prevent_remove_last_admin(store):
    team_id = store.create_team("Test Team", "user_1")
    assert store.remove_member(team_id, "user_1") == False # only admin
    
    store.invite_member(team_id, "user_2", "admin")
    assert store.remove_member(team_id, "user_1") == True # user_2 is still admin
    assert store.remove_member(team_id, "user_2") == False # now user_2 is last admin

def test_update_role(store):
    team_id = store.create_team("Test Team", "user_1")
    store.invite_member(team_id, "user_2", "member")
    
    assert store.update_role(team_id, "user_2", "admin") == True
    assert store.get_member_role(team_id, "user_2") == "admin"
    
    # demote last admin
    assert store.update_role(team_id, "user_1", "member") == True
    assert store.update_role(team_id, "user_2", "member") == False # last admin
