package com.owrawww.service;

import com.owrawww.domain.Inquiry;
import com.owrawww.domain.mapper.InquiryMapper;
import com.owrawww.util.AesUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;

@ExtendWith(MockitoExtension.class)
class InquiryServiceTest {

    @Mock
    private InquiryMapper inquiryMapper;

    @Mock
    private AesUtil aesUtil;

    @InjectMocks
    private InquiryService inquiryService;

    private Inquiry inquiry;

    @BeforeEach
    void setUp() {
        inquiry = new Inquiry();
        inquiry.setName("홍길동");
        inquiry.setEmail("hong@example.com");
        inquiry.setTel("010-1234-5678");
        inquiry.setTitle("도입 문의");
        inquiry.setContent("서비스 도입 관련 문의드립니다.");
        inquiry.setSolutionGubun("PG");
    }

    @Test
    @DisplayName("submit - 정상 입력 시 저장에 성공하고 true를 반환한다")
    void submit_success() {
        given(aesUtil.encrypt(inquiry.getTel())).willReturn("ENCRYPTED_TEL");
        given(aesUtil.encrypt(inquiry.getEmail())).willReturn("ENCRYPTED_EMAIL");
        given(aesUtil.hash(inquiry.getTel())).willReturn("HASH_TEL");
        given(aesUtil.hash(inquiry.getEmail())).willReturn("HASH_EMAIL");
        given(inquiryMapper.insert(any(Inquiry.class))).willReturn(1);

        boolean result = inquiryService.submit(inquiry);

        assertThat(result).isTrue();
        verify(inquiryMapper).insert(any(Inquiry.class));
    }

    @Test
    @DisplayName("submit - DB 저장 실패 시 false를 반환한다")
    void submit_dbFails_returnsFalse() {
        given(aesUtil.encrypt(any())).willReturn("ENCRYPTED");
        given(aesUtil.hash(any())).willReturn("HASHED");
        given(inquiryMapper.insert(any(Inquiry.class))).willReturn(0);

        boolean result = inquiryService.submit(inquiry);

        assertThat(result).isFalse();
    }

    @Test
    @DisplayName("submit - 전화번호와 이메일이 암호화 및 해시화되어 저장된다")
    void submit_encryptsAndHashesSensitiveFields() {
        given(aesUtil.encrypt("010-1234-5678")).willReturn("ENC_TEL");
        given(aesUtil.encrypt("hong@example.com")).willReturn("ENC_EMAIL");
        given(aesUtil.hash("010-1234-5678")).willReturn("HASH_TEL");
        given(aesUtil.hash("hong@example.com")).willReturn("HASH_EMAIL");
        given(inquiryMapper.insert(any(Inquiry.class))).willReturn(1);

        inquiryService.submit(inquiry);

        verify(aesUtil).encrypt("010-1234-5678");
        verify(aesUtil).encrypt("hong@example.com");
        verify(aesUtil).hash("010-1234-5678");
        verify(aesUtil).hash("hong@example.com");
    }
}
