package io.ljunggren.ups.api.service;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.Test;

import io.ljunggren.ups.api.model.UpsResponse;

public class BaseServiceTest {

    private final BaseService baseService = new BaseService("https://test.ups.com");

    private CloseableHttpResponse mockResponse(int statusCode, String body) throws IOException {
        CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class);
        StatusLine statusLine = mock(StatusLine.class);
        when(statusLine.getStatusCode()).thenReturn(statusCode);
        when(mockResponse.getStatusLine()).thenReturn(statusLine);
        HttpEntity entity = mock(HttpEntity.class);
        when(entity.getContent()).thenReturn(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
        when(mockResponse.getEntity()).thenReturn(entity);
        return mockResponse;
    }

    @Test
    public void getReturnsParsedResponseOnOk() throws IOException {
        CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse mockResponse = mockResponse(200, "{}");
        when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse);

        UpsResponse response = baseService.get(new HttpGet("https://test.ups.com/x"), httpClient);

        assertNotNull(response);
        assertEquals(200, response.getResponseCode());
        verify(httpClient).close();
    }

    @Test
    public void getReturnsParsedResponseOnInvalidRequest() throws IOException {
        CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse mockResponse = mockResponse(400, "{}");
        when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse);

        UpsResponse response = baseService.get(new HttpGet("https://test.ups.com/x"), httpClient);

        assertEquals(400, response.getResponseCode());
        verify(httpClient).close();
    }

    @Test
    public void getWrapsUnmappedStatusCodeAsError() throws IOException {
        CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse mockResponse = mockResponse(404, "not found body");
        when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse);

        UpsResponse response = baseService.get(new HttpGet("https://test.ups.com/x"), httpClient);

        assertEquals(404, response.getResponseCode());
        assertNotNull(response.getErrorResponse());
        assertEquals("Not found", response.getErrorResponse().getErrors().get(0).getCode());
        assertEquals("not found body", response.getErrorResponse().getErrors().get(0).getMessage());
    }

    @Test
    public void getWrapsExceptionAsErrorResponse() throws IOException {
        CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
        when(httpClient.execute(any(HttpUriRequest.class))).thenThrow(new IOException("connection refused"));

        UpsResponse response = baseService.get(new HttpGet("https://test.ups.com/x"), httpClient);

        assertNotNull(response.getErrorResponse());
        assertEquals("connection refused", response.getErrorResponse().getErrors().get(0).getMessage());
        verify(httpClient).close();
    }

    @Test
    public void getResultReadsMultiLineContentWithoutLosingBoundaries() throws IOException {
        CloseableHttpResponse mockResponse = mockResponse(200, "line one\nline two");

        String result = baseService.getResult(mockResponse);

        assertEquals("line one\nline two", result);
    }

    @Test
    public void generateBearerHeadersIncludesExpectedHeaders() {
        org.apache.http.Header[] headers = baseService.generateBearerHeaders("my-token");

        assertEquals(3, headers.length);
        assertEquals("transId", headers[0].getName());
        assertTrue(headers[0].getValue().matches("[0-9a-f-]{36}"));
        assertEquals("transactionSrc", headers[1].getName());
        assertEquals("https://test.ups.com", headers[1].getValue());
        assertEquals("Authorization", headers[2].getName());
        assertEquals("Bearer my-token", headers[2].getValue());
    }

}
