package com.cloudhandson.vpdbackoffice.service;

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

import com.cloudhandson.vpdbackoffice.domain.protectedobject.ProtectedColumn;
import com.cloudhandson.vpdbackoffice.domain.protectedobject.ProtectedObject;
import com.cloudhandson.vpdbackoffice.mapper.OrdsMetadataMapper;
import java.util.List;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;

class OrdsMetadataServiceTest {

  @Test
  void generatedObjectHandlerIncludesTokenSpecificVpdSqlTrace() {
    OrdsMetadataMapper mapper = mock(OrdsMetadataMapper.class);
    ProtectedObjectService protectedObjectService = mock(ProtectedObjectService.class);
    DataSource dataSource = mock(DataSource.class);
    ProtectedObject object = new ProtectedObject(
        7L,
        "ADMIN",
        "CB_V_SEARCH_DOCUMENTS",
        "cb-ords/cb-object-query/admin/cb_v_search_documents",
        "Y"
    );
    when(protectedObjectService.assertEnabled(7L)).thenReturn(object);
    when(protectedObjectService.findColumns(7L)).thenReturn(List.of(
        new ProtectedColumn(1L, 7L, "DOC_ID", "N", null, "PUBLIC", "NONE"),
        new ProtectedColumn(2L, 7L, "DEPT_CODE", "N", null, "INTERNAL", "NONE")
    ));

    OrdsMetadataService service = new OrdsMetadataService(
        mapper,
        new JdbcTemplate(dataSource),
        protectedObjectService,
        dataSource,
        "",
        "",
        ""
    );

    String source = service.objectQueryHandlerSource(7L);

    assertThat(source)
        .contains("cb_ords_handler_pkg.set_vpd_context(:auth_header, :probe_id)")
        .contains("admin.cb_agent_doc_vpd_filter('ADMIN', 'CB_V_SEARCH_DOCUMENTS')")
        .contains("v_vpd_predicate")
        .contains("APEX_JSON.WRITE('effective_sql', v_effective_sql)")
        .contains("SELECT o.DOC_ID, o.DEPT_CODE FROM ADMIN.CB_V_SEARCH_DOCUMENTS o");
  }
}
