package com.xly.erp.module.usr.mapper;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@ActiveProfiles("test")
class PermissionCategoryMapperIT {

    @Autowired
    private PermissionCategoryMapper permissionCategoryMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @BeforeEach
    @AfterEach
    void cleanup() {
        jdbcTemplate.update("DELETE FROM tPermissionCategory WHERE sCategoryCode LIKE 'sp_test_%'");
    }

    @Test
    void countActiveByIds_returnsCorrectCount() {
        Integer cat1 = insertCategory("sp_test_c1", "权限1", false);
        Integer cat2 = insertCategory("sp_test_c2", "权限2", false);
        Integer cat3 = insertCategory("sp_test_c3", "权限3", true);

        assertThat(permissionCategoryMapper.countActiveByIds(List.of(cat1, cat2, cat3))).isEqualTo(2);
        assertThat(permissionCategoryMapper.countActiveByIds(List.of(cat1, 99999991))).isEqualTo(1);
        assertThat(permissionCategoryMapper.countActiveByIds(List.of(99999991))).isZero();
    }

    private Integer insertCategory(String code, String name, boolean deleted) {
        jdbcTemplate.update(
                "INSERT INTO tPermissionCategory (sBrandsId, sSubsidiaryId, tCreateDate, sCategoryCode, sCategoryName, "
                        + "iSortOrder, sCreatedBy, bDeleted) "
                        + "VALUES ('XLY','XLY', NOW(), ?, ?, 0, 'STUB_ADMIN', ?)",
                code, name, deleted ? 1 : 0);
        return jdbcTemplate.queryForObject(
                "SELECT iIncrement FROM tPermissionCategory WHERE sCategoryCode = ?", Integer.class, code);
    }
}
