package ch.unisg.roster.roster.adapter.in.web;


import ch.unisg.common.valueobject.ExecutorURI;
import ch.unisg.roster.roster.adapter.out.persistence.mongodb.RosterRepository;
import ch.unisg.roster.roster.application.port.in.ApplyForTaskCommand;
import ch.unisg.roster.roster.application.port.in.ApplyForTaskUseCase;
import ch.unisg.roster.roster.domain.ExecutorInfo;
import ch.unisg.roster.roster.domain.RosterItem;
import ch.unisg.roster.roster.domain.Task;
import ch.unisg.roster.roster.domain.valueobject.ExecutorType;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.BDDMockito.then;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(controllers = ApplyForTaskController.class)
public class ApplyForTaskControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ApplyForTaskUseCase applyForTaskUseCase;

    @MockBean
    RosterRepository rosterRepository;

    @Test
    void testApplyForTask() throws Exception{

        String executorType = "test-type";
        String executorURI = "test-uri";
        String taskId = "test-id";

        String jsonPayLoad = new JSONObject()
            .put("executorType", executorType )
            .put("executorUri",executorURI)
            .toString();

        RosterItem rosterItem = new RosterItem(taskId, executorType,
            new ExecutorURI(executorURI));

        Task taskStub = new Task(taskId, executorType);

        ApplyForTaskCommand applyForTaskCommand = new ApplyForTaskCommand(new ExecutorType(executorType),
            new ExecutorURI(executorURI));

        Mockito.when(applyForTaskUseCase.applyForTask(applyForTaskCommand))
            .thenReturn(taskStub);

        // TODO Add slash at the front
        mockMvc.perform(post("tasks/apply/")
            .contentType("application/json")
            .content(jsonPayLoad))
            .andExpect(status().isCreated());

        then(applyForTaskUseCase).should()
            .applyForTask(new ApplyForTaskCommand(new ExecutorType(executorType),
                new ExecutorURI(executorURI)));

    }
}
