package kr.itn.itnhub.config;

import kr.itn.itnhub.AbstractDbTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@AutoConfigureMockMvc
class SecurityConfigTest extends AbstractDbTest {

    @Autowired
    MockMvc mvc;

    @Test
    void 인증없이_api를_부르면_401이다() throws Exception {
        mvc.perform(get("/api/orgs"))
                .andExpect(status().isUnauthorized());
    }

    @Test
    void 올바른_비밀번호로_로그인하면_200이다() throws Exception {
        mvc.perform(post("/api/auth/login")
                        .param("username", "admin")
                        .param("password", "test-password")
                        .with(csrf()))
                .andExpect(status().isOk());
    }

    @Test
    void 틀린_비밀번호로_로그인하면_401이다() throws Exception {
        mvc.perform(post("/api/auth/login")
                        .param("username", "admin")
                        .param("password", "wrong")
                        .with(csrf()))
                .andExpect(status().isUnauthorized());
    }

    @Test
    void 로그인_엔드포인트는_인증없이_접근할_수_있다() throws Exception {
        mvc.perform(post("/api/auth/login")
                        .param("username", "nobody")
                        .param("password", "nothing")
                        .with(csrf()))
                .andExpect(status().isUnauthorized()); // 403이 아니라 401이어야 한다
    }
}
