package com.sonymusic

import hudson.model.AbstractBuild
import hudson.model.Job
import hudson.model.Result
import jenkins.model.Jenkins
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.mockito.MockedStatic

import static org.junit.jupiter.api.Assertions.assertEquals
import static org.junit.jupiter.api.Assertions.assertNull
import static org.mockito.Mockito.*

class MetadataUtilsTest {

    @Nested
    class GetLastCompletedBuildStatusTest {
        private MockedStatic<Jenkins> mockStaticJenkins
        private Jenkins jenkins
        private Job workflowJob
        private AbstractBuild build

        @BeforeEach
        void setUp() {
            mockStaticJenkins = mockStatic(Jenkins.class)
            jenkins = mock(Jenkins.class)
            workflowJob = mock(Job.class)
            build = mock(AbstractBuild.class)
        }

        @AfterEach
        void cleanUp() {
            mockStaticJenkins.close()
        }

        @Test
        void testSuccess() {
            mockStaticJenkins.when({Jenkins.getInstance()}).thenReturn(jenkins)
            when(jenkins.getItemByFullName("test/job")).thenReturn(workflowJob)
            when(workflowJob.getLastCompletedBuild()).thenReturn(build)
            when(build.getResult()).thenReturn(Result.SUCCESS)
            assertEquals(MetadataUtils.getLastCompletedBuildStatus("test/job"), Result.SUCCESS)
        }

        @Test
        void testNonExistantJob() {
            mockStaticJenkins.when({Jenkins.getInstance()}).thenReturn(jenkins)
            when(jenkins.getItemByFullName("test/job")).thenReturn(null)
            assertNull(MetadataUtils.getLastCompletedBuildStatus("test/job"))
        }

        @Test
        void testJobWithoutBuilds() {
            mockStaticJenkins.when({Jenkins.getInstance()}).thenReturn(jenkins)
            when(jenkins.getItemByFullName("test/job")).thenReturn(workflowJob)
            when(workflowJob.getLastCompletedBuild()).thenReturn(null)
            assertNull(MetadataUtils.getLastCompletedBuildStatus("test/job"))
        }

        @Test
        void testJobBuildWithoutStatus() {
            mockStaticJenkins.when({Jenkins.getInstance()}).thenReturn(jenkins)
            when(jenkins.getItemByFullName("test/job")).thenReturn(workflowJob)
            when(workflowJob.getLastCompletedBuild()).thenReturn(build)
            when(build.getResult()).thenReturn(null)

            assertNull(MetadataUtils.getLastCompletedBuildStatus("test/job"))
        }
    }
}
