package com.cloudhandson.vpdbackoffice.service;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;

import com.cloudhandson.vpdbackoffice.domain.vector.VectorQueryEmbedding;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;

class VectorKnowledgeServiceTest {

  @Test
  void vectorizesPlainTextWithTheLocalEmbeddingAndBuildsOrdsBody() {
    OpenAiCompatibleClient embeddingClient = mock(OpenAiCompatibleClient.class);
    VectorKnowledgeService service = service(embeddingClient);

    VectorQueryEmbedding result = service.vectorizeQuery("  Oracle VPD에서 ORDS 권한 확인  ", "demo");

    assertThat(result.query()).isEqualTo("Oracle VPD에서 ORDS 권한 확인");
    assertThat(result.embeddingMode()).isEqualTo("DEMO");
    assertThat(result.embeddingModel()).isEqualTo("로컬 임베딩(개발용)");
    assertThat(result.requestBody()).startsWith("{\"embedding\":[").contains("]}");
  }

  @Test
  void rejectsAiModeWhenEmbeddingConfigurationIsMissing() {
    OpenAiCompatibleClient embeddingClient = mock(OpenAiCompatibleClient.class);
    VectorKnowledgeService service = service(embeddingClient);

    assertThatThrownBy(() -> service.vectorizeQuery("검색어", "AI"))
        .isInstanceOf(AppException.class)
        .hasMessageContaining("AI 임베딩이 설정되지 않았습니다");
  }

  @Test
  void rejectsBlankPlainTextBeforeCallingOrds() {
    VectorKnowledgeService service = service(mock(OpenAiCompatibleClient.class));

    assertThatThrownBy(() -> service.vectorizeQuery("  ", "DEMO"))
        .isInstanceOf(AppException.class)
        .hasMessageContaining("검색 질문");
  }

  private VectorKnowledgeService service(OpenAiCompatibleClient embeddingClient) {
    return new VectorKnowledgeService(
        mock(JdbcTemplate.class),
        new ObjectMapper(),
        embeddingClient,
        mock(ProtectedObjectService.class),
        mock(BearerTokenService.class),
        mock(OrdsProbeService.class));
  }
}
