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

import static org.junit.jupiter.api.Assertions.assertEquals;
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.user.region.SysRegionConfig;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

class SysRegionConfigServiceImplTest {

  private static final String REGION_ID = "2051777551323426818";
  private static final String REGION_NAME = "东南亚区";

  private MongoTemplate mongoTemplate;
  private SysRegionConfigServiceImpl service;

  @BeforeEach
  void setUp() {
    mongoTemplate = mock(MongoTemplate.class);
    service = new SysRegionConfigServiceImpl(mongoTemplate);
  }

  @Test
  void mapRegionName_shouldKeepFirstWhenMongoReturnsDuplicateIds() {
    when(mongoTemplate.find(any(Query.class), eq(SysRegionConfig.class))).thenReturn(List.of(
        region(REGION_ID, "SEA", REGION_NAME),
        region(REGION_ID, "SEA", REGION_NAME)
    ));

    Map<String, String> result = service.mapRegionName("LIKEI");

    assertEquals(Map.of(REGION_ID, REGION_NAME), result);
  }

  @Test
  void mapAvailable_shouldKeepFirstWhenMongoReturnsDuplicateIds() {
    when(mongoTemplate.find(any(Query.class), eq(SysRegionConfig.class))).thenReturn(List.of(
        region(REGION_ID, "SEA", REGION_NAME),
        region(REGION_ID, "SEA2", REGION_NAME)
    ));

    Map<String, SysRegionConfig> result = service.mapAvailable(Set.of(REGION_ID));

    assertEquals(1, result.size());
    assertEquals("SEA", result.get(REGION_ID).getRegionCode());
  }

  private SysRegionConfig region(String id, String regionCode, String regionName) {
    return new SysRegionConfig()
        .setId(id)
        .setRegionCode(regionCode)
        .setRegionName(regionName)
        .setDel(Boolean.FALSE);
  }
}
