package com.red.circle.other.infra.database.mongo.service.team.team.impl;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.red.circle.other.infra.database.mongo.entity.team.team.TeamMember;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamProfile;
import com.red.circle.other.inner.enums.team.TeamMemberRole;
import com.red.circle.other.inner.model.cmd.team.TeamTableQryCmd;
import com.red.circle.other.inner.model.dto.agency.agency.TeamStatus;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

class TeamProfileServiceImplTest {

  @Test
  void listShouldHideAvailableProfileWithoutCurrentOwnerMember() {
    MongoTemplate mongoTemplate = mock(MongoTemplate.class);
    TeamProfileServiceImpl service = new TeamProfileServiceImpl(mongoTemplate);

    TeamProfile orphanAvailable = profile(1L, 10L, TeamStatus.AVAILABLE);
    TeamProfile currentAvailable = profile(2L, 20L, TeamStatus.AVAILABLE);
    TeamProfile closed = profile(3L, 30L, TeamStatus.CLOSE);

    when(mongoTemplate.find(any(Query.class), eq(TeamProfile.class)))
        .thenReturn(List.of(orphanAvailable, currentAvailable, closed));
    when(mongoTemplate.find(any(Query.class), eq(TeamMember.class)))
        .thenReturn(List.of(member(2L, 20L, TeamMemberRole.OWN)));

    List<TeamProfile> result = service.list(new TeamTableQryCmd());

    assertEquals(List.of(currentAvailable, closed), result);
  }

  @Test
  void getAvailableByOwnUserIdShouldIgnoreProfileWithoutCurrentOwnerMember() {
    MongoTemplate mongoTemplate = mock(MongoTemplate.class);
    TeamProfileServiceImpl service = new TeamProfileServiceImpl(mongoTemplate);

    when(mongoTemplate.find(any(Query.class), eq(TeamProfile.class)))
        .thenReturn(List.of(profile(1L, 10L, TeamStatus.AVAILABLE)));
    when(mongoTemplate.find(any(Query.class), eq(TeamMember.class))).thenReturn(List.of());

    assertNull(service.getAvailableByOwnUserId(10L));
  }

  private TeamProfile profile(Long teamId, Long ownUserId, TeamStatus status) {
    return new TeamProfile()
        .setId(teamId)
        .setOwnUserId(ownUserId)
        .setStatus(status);
  }

  private TeamMember member(Long teamId, Long memberId, TeamMemberRole role) {
    return new TeamMember()
        .setTeamId(teamId)
        .setMemberId(memberId)
        .setRole(role);
  }
}
