package org.fuseri.moduleexercise.answer;

import jakarta.persistence.EntityNotFoundException;
import org.fuseri.moduleexercise.exercise.Exercise;
import org.fuseri.moduleexercise.question.Question;
import org.junit.jupiter.api.Assertions;
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.boot.test.mock.mockito.MockBean;
import java.util.HashSet;
import java.util.Optional;

import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@SpringBootTest
class AnswerServiceTest {

    @Autowired
    AnswerService service;

    @MockBean
    AnswerRepository answerRepository;

    Answer answer;
    Question question;
    Exercise exercise;

    @BeforeEach
    void setup() {
        exercise = new Exercise("idioms", "exercise on basic idioms", 2, 1L, new HashSet<>());
        question = new Question("text", new HashSet<>(), exercise);
        answer = new Answer("text", false, question);
    }


    @Test
    void create() {
        when(answerRepository.save(answer)).thenReturn(answer);
        Answer result = service.create(answer);
        Assertions.assertEquals(answer, result);
        verify(answerRepository).save(answer);
    }

    @Test
    void notFound() {
        when(answerRepository.findById(anyLong())).thenReturn(Optional.empty());
        Assertions.assertThrows(EntityNotFoundException.class, () -> service.find(anyLong()));
    }

    @Test
    void find() {
        when(answerRepository.findById(anyLong())).thenReturn(Optional.of(answer));

        Answer result = service.find(anyLong());

        Assertions.assertEquals(answer, result);
        verify(answerRepository).findById(anyLong());
    }
}
