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 static org.assertj.core.api.Assertions.assertThat;

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

    @Autowired
    private StaffMapper staffMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

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

    @Test
    void existsActiveById_handlesAliveDeletedMissing() {
        Integer aliveId = insertStaff("sp_test_st_alive", "活的", false);
        Integer deletedId = insertStaff("sp_test_st_dead", "死的", true);

        assertThat(staffMapper.existsActiveById(aliveId)).isTrue();
        assertThat(staffMapper.existsActiveById(deletedId)).isFalse();
        assertThat(staffMapper.existsActiveById(99999990)).isFalse();
    }

    private Integer insertStaff(String staffNo, String staffName, boolean deleted) {
        jdbcTemplate.update(
                "INSERT INTO tStaff (sBrandsId, sSubsidiaryId, tCreateDate, sStaffNo, sStaffName, sCreatedBy, bDeleted) "
                        + "VALUES ('XLY','XLY', NOW(), ?, ?, 'STUB_ADMIN', ?)",
                staffNo, staffName, deleted ? 1 : 0);
        return jdbcTemplate.queryForObject(
                "SELECT iIncrement FROM tStaff WHERE sStaffNo = ?", Integer.class, staffNo);
    }
}
