package com.securityc4po.api.pentest

import com.fasterxml.jackson.databind.ObjectMapper
import com.github.tomakehurst.wiremock.common.Json
import com.securityc4po.api.BaseDocumentationIntTest
import com.securityc4po.api.configuration.NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR
import com.securityc4po.api.configuration.RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE
import com.securityc4po.api.configuration.SIC_INNER_SHOULD_BE_STATIC
import com.securityc4po.api.project.PentestState
import com.securityc4po.api.project.Project
import com.securityc4po.api.project.ProjectEntity
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Query
import org.springframework.restdocs.operation.preprocess.Preprocessors
import org.springframework.restdocs.payload.JsonFieldType
import org.springframework.restdocs.payload.PayloadDocumentation
import org.springframework.restdocs.request.RequestDocumentation
import org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation
import reactor.core.publisher.Mono

@SuppressFBWarnings(
    SIC_INNER_SHOULD_BE_STATIC,
    NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR,
    RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE
)
class PentestControllerDocumentationTest : BaseDocumentationIntTest() {

    @Autowired
    lateinit var mongoTemplate: MongoTemplate
    var mapper = ObjectMapper()

    @BeforeEach
    fun init() {
        configureAdminToken()
        persistBasicTestScenario()
    }

    @AfterEach
    fun destroy() {
        cleanUp()
    }

    @Nested
    inner class GetPentests {
        @Test
        fun getPentestsByProjectIdAndCategory() {
            val projectId = "d2e126ba-f608-11ec-b939-0242ac120025"
            val category = "INFORMATION_GATHERING"
            webTestClient.get()
                .uri("/pentests?projectId={projectId}&category={category}", projectId, category)
                .header("Authorization", "Bearer $tokenAdmin")
                .exchange()
                .expectStatus().isOk
                .expectHeader().doesNotExist("")
                .expectBody().json(Json.write(getProjectsResponse()))
                .consumeWith(
                    WebTestClientRestDocumentation.document(
                        "{methodName}",
                        Preprocessors.preprocessRequest(
                            Preprocessors.prettyPrint(),
                            Preprocessors.modifyUris().removePort(),
                            Preprocessors.removeHeaders("Host", "Content-Length")
                        ),
                        Preprocessors.preprocessResponse(
                            Preprocessors.prettyPrint()
                        ),
                        RequestDocumentation.relaxedRequestParameters(
                            RequestDocumentation.parameterWithName("projectId")
                                .description("The id of the project you want to get the pentests for"),
                            RequestDocumentation.parameterWithName("category")
                                .description("The category you want to get the pentests for")
                        ),
                        PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation.fieldWithPath("[].id").type(JsonFieldType.STRING)
                                .description("The id of the requested pentest"),
                            PayloadDocumentation.fieldWithPath("[].projectId").type(JsonFieldType.STRING)
                                .description("The id of the project of the requested pentest"),
                            PayloadDocumentation.fieldWithPath("[].category").type(JsonFieldType.STRING)
                                .description("The category of the requested pentest"),
                            PayloadDocumentation.fieldWithPath("[].refNumber").type(JsonFieldType.STRING)
                                .description("The reference number of the requested pentest according to the current OWASP Testing Guide"),
                            PayloadDocumentation.fieldWithPath("[].status").type(JsonFieldType.STRING)
                                .description("The status of the requested pentest"),
                            PayloadDocumentation.fieldWithPath("[].enabled").type(JsonFieldType.BOOLEAN)
                                .description("Shows you if the objective of the pentest is enabled or not"),
                            PayloadDocumentation.fieldWithPath("[].findingIds").type(JsonFieldType.ARRAY)
                                .description("List of ids of the findings in the requested pentest"),
                            PayloadDocumentation.fieldWithPath("[].commentIds").type(JsonFieldType.ARRAY)
                                .description("List of ids of the comments of the requested pentest"),
                            PayloadDocumentation.fieldWithPath("[].timeSpent").type(JsonFieldType.NUMBER)
                                .description("Time spent on the pentest")
                        )
                    )
                )
        }

        private val pentestOne = Pentest(
            id = "9c8af320-f608-11ec-b939-0242ac120002",
            projectId = "d2e126ba-f608-11ec-b939-0242ac120025",
            category = PentestCategory.INFORMATION_GATHERING,
            refNumber = "OTG-INFO-001",
            status = PentestStatus.NOT_STARTED,
            enabled = true,
            findingIds = emptyList(),
            commentIds = emptyList(),
            timeSpent = 0
        )
        private val pentestTwo = Pentest(
            id = "43fbc63c-f624-11ec-b939-0242ac120002",
            projectId = "d2e126ba-f608-11ec-b939-0242ac120025",
            category = PentestCategory.INFORMATION_GATHERING,
            refNumber = "OTG-INFO-002",
            status = PentestStatus.IN_PROGRESS,
            enabled = true,
            findingIds = emptyList(),
            commentIds = emptyList(),
            timeSpent = 0
        )

        private fun getProjectsResponse() = listOf(
            pentestOne.toPentestResponseBody(),
            pentestTwo.toPentestResponseBody()
        )
    }

    @Nested
    inner class SavePentest {
        @Test
        fun savePentestByProjectId() {
            val projectId = "d2e126ba-f608-11ec-b939-0242ac120025"
            webTestClient.post()
                .uri("/pentests/{projectId}", projectId)
                .header("Authorization", "Bearer $tokenAdmin")
                .body(Mono.just(newPentestBody), PentestRequestBody::class.java)
                .exchange()
                .expectStatus().isAccepted
                .expectHeader().doesNotExist("")
                .expectBody().json(Json.write(newPentestBody))
                .consumeWith(
                    WebTestClientRestDocumentation.document(
                        "{methodName}",
                        Preprocessors.preprocessRequest(
                            Preprocessors.prettyPrint(),
                            Preprocessors.modifyUris().removePort(),
                            Preprocessors.removeHeaders("Host", "Content-Length")
                        ),
                        Preprocessors.preprocessResponse(
                            Preprocessors.prettyPrint()
                        ),
                        RequestDocumentation.relaxedPathParameters(
                            RequestDocumentation.parameterWithName("projectId")
                                .description("The id of the project you want to save the pentest for")
                        ),
                        PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation.fieldWithPath("id").type(JsonFieldType.STRING)
                                .description("The id of the created pentest"),
                            PayloadDocumentation.fieldWithPath("projectId").type(JsonFieldType.STRING)
                                .description("The id of the project of the created pentest"),
                            PayloadDocumentation.fieldWithPath("category").type(JsonFieldType.STRING)
                                .description("The category of the created pentest"),
                            PayloadDocumentation.fieldWithPath("refNumber").type(JsonFieldType.STRING)
                                .description("The reference number of the created pentest according to the current OWASP Testing Guide"),
                            PayloadDocumentation.fieldWithPath("status").type(JsonFieldType.STRING)
                                .description("The status of the created pentest"),
                            PayloadDocumentation.fieldWithPath("enabled").type(JsonFieldType.BOOLEAN)
                                .description("Shows you if the objective of the pentest is enabled or not"),
                            PayloadDocumentation.fieldWithPath("findingIds").type(JsonFieldType.ARRAY)
                                .description("List of ids of the findings in the created pentest"),
                            PayloadDocumentation.fieldWithPath("commentIds").type(JsonFieldType.ARRAY)
                                .description("List of ids of the comments of the created pentest"),
                            PayloadDocumentation.fieldWithPath("timeSpent").type(JsonFieldType.NUMBER)
                                .description("Time spent on the pentest")
                        )
                    )
                )
        }

        val newPentestBody = PentestRequestBody(
            projectId = "d2e126ba-f608-11ec-b939-0242ac120025",
            category = "CLIENT_SIDE_TESTING",
            refNumber = "OTG-CLIENT-001",
            status = "IN_PROGRESS",
            enabled = true,
            findingIds = emptyList<String>(),
            commentIds = emptyList<String>(),
            timeSpent = 0
        )
    }

    @Nested
    inner class UpdatePentest {
        @Test
        fun updatePentestByProjectId() {
            val pentestOneId = "9c8af320-f608-11ec-b939-0242ac120002"
            webTestClient.patch()
                .uri("/pentests/{pentestId}", pentestOneId)
                .header("Authorization", "Bearer $tokenAdmin")
                .body(Mono.just(pentestOneBody), PentestRequestBody::class.java)
                .exchange()
                .expectStatus().isAccepted
                .expectHeader().doesNotExist("")
                .expectBody().json(Json.write(pentestOneBody))
                .consumeWith(
                    WebTestClientRestDocumentation.document(
                        "{methodName}",
                        Preprocessors.preprocessRequest(
                            Preprocessors.prettyPrint(),
                            Preprocessors.modifyUris().removePort(),
                            Preprocessors.removeHeaders("Host", "Content-Length")
                        ),
                        Preprocessors.preprocessResponse(
                            Preprocessors.prettyPrint()
                        ),
                        RequestDocumentation.relaxedPathParameters(
                            RequestDocumentation.parameterWithName("pentestId")
                                .description("The id of the pentest you want to update")
                        ),
                        PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation.fieldWithPath("id").type(JsonFieldType.STRING)
                                .description("The id of the updated pentest"),
                            PayloadDocumentation.fieldWithPath("projectId").type(JsonFieldType.STRING)
                                .description("The id of the project of the updated pentest"),
                            PayloadDocumentation.fieldWithPath("category").type(JsonFieldType.STRING)
                                .description("The category of the updated pentest"),
                            PayloadDocumentation.fieldWithPath("refNumber").type(JsonFieldType.STRING)
                                .description("The reference number of the updated pentest according to the current OWASP Testing Guide"),
                            PayloadDocumentation.fieldWithPath("status").type(JsonFieldType.STRING)
                                .description("The status of the updated pentest"),
                            PayloadDocumentation.fieldWithPath("enabled").type(JsonFieldType.BOOLEAN)
                                .description("Shows you if the objective of the pentest is enabled or not"),
                            PayloadDocumentation.fieldWithPath("findingIds").type(JsonFieldType.ARRAY)
                                .description("List of ids of the findings in the updated pentest"),
                            PayloadDocumentation.fieldWithPath("commentIds").type(JsonFieldType.ARRAY)
                                .description("List of ids of the comments of the updated pentest"),
                            PayloadDocumentation.fieldWithPath("timeSpent").type(JsonFieldType.NUMBER)
                                .description("Time spent on the pentest")
                        )
                    )
                )
        }

        val pentestOneBody = PentestRequestBody(
            projectId = "d2e126ba-f608-11ec-b939-0242ac120025",
            category = "INFORMATION_GATHERING",
            refNumber = "OTG-INFO-001",
            status = "PAUSED",
            enabled = true,
            findingIds = emptyList<String>(),
            commentIds = emptyList<String>(),
            timeSpent = 0
        )
    }

    private fun persistBasicTestScenario() {
        // setup test data
        // Project
        val projectOne = Project(
            id = "d2e126ba-f608-11ec-b939-0242ac120025",
            client = "E Corp",
            title = "Some Mock API (v1.0) Scanning",
            createdAt = "2021-01-10T18:05:00Z",
            tester = "Novatester",
            projectPentests = emptyList(),
            state = PentestState.NEW,
            version = "1.0",
            createdBy = "f8aab31f-4925-4242-a6fa-f98135b4b032"
        )
        // Pentests
        val pentestOne = Pentest(
            id = "9c8af320-f608-11ec-b939-0242ac120002",
            projectId = "d2e126ba-f608-11ec-b939-0242ac120025",
            category = PentestCategory.INFORMATION_GATHERING,
            refNumber = "OTG-INFO-001",
            status = PentestStatus.NOT_STARTED,
            enabled = true,
            findingIds = emptyList(),
            commentIds = emptyList(),
            timeSpent = 0
        )
        val pentestTwo = Pentest(
            id = "43fbc63c-f624-11ec-b939-0242ac120002",
            projectId = "d2e126ba-f608-11ec-b939-0242ac120025",
            category = PentestCategory.INFORMATION_GATHERING,
            refNumber = "OTG-INFO-002",
            status = PentestStatus.IN_PROGRESS,
            enabled = true,
            findingIds = emptyList(),
            commentIds = emptyList(),
            timeSpent = 0
        )
        val pentestThree = Pentest(
            id = "74eae112-f62c-11ec-b939-0242ac120002",
            projectId = "d2e126ba-f608-11ec-b939-0242ac120025",
            category = PentestCategory.AUTHENTICATION_TESTING,
            refNumber = "OTG-AUTHN-001",
            status = PentestStatus.COMPLETED,
            enabled = true,
            findingIds = emptyList(),
            commentIds = emptyList(),
            timeSpent = 0
        )
        // persist test data in database
        mongoTemplate.save(ProjectEntity(projectOne))
        mongoTemplate.save(PentestEntity(pentestOne))
        mongoTemplate.save(PentestEntity(pentestTwo))
        mongoTemplate.save(PentestEntity(pentestThree))
    }

    private fun configureAdminToken() {
        tokenAdmin = getAccessToken("test_admin", "test", "c4po_local", "c4po_realm_local")
    }

    private fun cleanUp() {
        mongoTemplate.findAllAndRemove(Query(), ProjectEntity::class.java)
        mongoTemplate.findAllAndRemove(Query(), PentestEntity::class.java)

        tokenAdmin = "n/a"
    }
}