package kr.itn.itnhub.code;

import kr.itn.itnhub.AbstractDbTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;

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

class CodeSchemaTest extends AbstractDbTest {

    @Autowired
    JdbcTemplate jdbc;

    @Test
    void 코드_테이블이_생성된다() {
        Integer count = jdbc.queryForObject(
                "select count(*) from information_schema.tables "
                        + "where table_schema = 'itnhub' and table_name in ('code_group', 'code')",
                Integer.class);

        assertThat(count).isEqualTo(2);
    }

    @Test
    void 그룹과_코드_조합이_유일하다() {
        jdbc.update("insert into code_group (group_id, group_name) values ('TEST_GRP', '테스트')");
        jdbc.update("insert into code (group_id, code, label, sort_order) "
                + "values ('TEST_GRP', 'A', '가', 1)");

        assertThatThrownBy(() -> jdbc.update(
                "insert into code (group_id, code, label, sort_order) "
                        + "values ('TEST_GRP', 'A', '다른라벨', 2)"))
                .isInstanceOf(DataIntegrityViolationException.class);

        jdbc.update("delete from code where group_id = 'TEST_GRP'");
        jdbc.update("delete from code_group where group_id = 'TEST_GRP'");
    }

    @Test
    void 없는_그룹의_코드는_넣을_수_없다() {
        assertThatThrownBy(() -> jdbc.update(
                "insert into code (group_id, code, label, sort_order) "
                        + "values ('NO_SUCH_GROUP', 'A', '가', 1)"))
                .isInstanceOf(DataIntegrityViolationException.class);
    }

    @Test
    void attrs는_기본값이_빈_객체다() {
        jdbc.update("insert into code_group (group_id, group_name) values ('TEST_ATTR', '테스트')");
        jdbc.update("insert into code (group_id, code, label, sort_order) "
                + "values ('TEST_ATTR', 'A', '가', 1)");

        String attrs = jdbc.queryForObject(
                "select attrs::text from code where group_id = 'TEST_ATTR' and code = 'A'",
                String.class);

        assertThat(attrs).isEqualTo("{}");

        jdbc.update("delete from code where group_id = 'TEST_ATTR'");
        jdbc.update("delete from code_group where group_id = 'TEST_ATTR'");
    }
}
