package ch.unisg.roster.roster;


import ch.unisg.roster.roster.application.port.in.AddRosterItemPort;
import ch.unisg.roster.roster.domain.Roster;
import org.json.JSONObject;
import org.json.JSONException;
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.web.client.TestRestTemplate;
import org.springframework.http.*;

import static org.assertj.core.api.BDDAssertions.*;


@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class AddNewAssignmentToRosterServiceSystemTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private AddRosterItemPort addRosterItemPort;

    @Test
    void addNewAssignmentToRosterService() throws JSONException {

        String rosterItemId = "test-id";
        String executorType = "test-type";
        String executorURI = "test-URI";

        ResponseEntity response = whenAddNewAssignmentToRoster(rosterItemId, executorType, executorURI);

        JSONObject responseJson = new JSONObject(response.getBody().toString());
        String respRosterItemId = responseJson.getString("rosterItemId");
        String respExecutorType = responseJson.getString("executorType");
        String respExecutorURI = responseJson.getString("executorURI");

        then(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        then(respRosterItemId).isEqualTo(rosterItemId);
        then(respExecutorType).isEqualTo(executorType);
        then(respExecutorURI).isEqualTo(executorURI);
        then(Roster.getInstance().getRosterMap().size()).isEqualTo(1);


    }

    private ResponseEntity whenAddNewAssignmentToRoster(
        String rosterItemId,
        String executorType,
        String executorURI) throws JSONException {

        Roster.getInstance().getRosterMap().clear();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");

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

        HttpEntity<String> request = new HttpEntity<>(jsonPayLoad, headers);

        return restTemplate.exchange(
            "/tasks/apply/",
            HttpMethod.POST,
            request,
            Object.class
        );
    }



}
