package com.sonymusic

import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test

import static org.junit.jupiter.api.Assertions.assertEquals

class GithubPostPrCommentTest extends BaseGlobalVarTest {
    def githubPostPrComment
    def response = [id: '123']

    @BeforeEach
    void setUp() {
        super.setUp()
        githubPostPrComment = loadScript('vars/githubPostPrComment.groovy')
        binding.setVariable('env', ['CHANGE_ID': '100'])
        helper.registerAllowedMethod('withCredentials', [Map])
        helper.registerAllowedMethod('sh', [Map])
        helper.registerAllowedMethod('readJSON', [Map], {
            return response
        })
    }

    @Test
    void testCallWithNoArgs() {
        assertThrowsWithMessage(
            IllegalArgumentException.class, 
            "githubPostPrComment: Missing required parameter: 'message'", 
            { githubPostPrComment.call(repo: 'test') }
        )
        assertThrowsWithMessage(
            IllegalArgumentException.class, 
            "githubPostPrComment: Missing required parameter: 'repo'", 
            { githubPostPrComment.call(message: 'test') }
        )
    }

    @Test
    void testCallWithNoPullRequestId() {
        binding.setVariable('env', [:])

        assertThrowsWithMessage(
            AssertionError.class, 
            "githubPostPrComment: pullRequestId is required if env.CHANGE_ID is not available.", 
            { githubPostPrComment.call(repo: 'frontend-test', message: 'test') }
        )
    }

    @Test
    void testCallSuccess() {
        def comment = githubPostPrComment(
            repo: 'frontend-test',
            message: 'test message'
        )

        assertMethodCalledOnceWith('withCredentials', '[GITHUB_TOKEN]')
        assertMethodCalledOnceWith('sh', [
            '"body": "test message"',
            'curl -X POST -H "Authorization: token \${GITHUB_TOKEN}"',
            'https://api.github.com/repos/theorchard/frontend-test/issues/100/comments'
        ])

        assertEquals(comment, response)
    }

    @Test
    void testCallWithOwner() {
        githubPostPrComment(
            repo: 'frontend-test',
            message: 'test message',
            owner: 'sme'
        )

        assertMethodCalledTimes('withCredentials', 1)
        assertMethodCalledOnceWith('sh', [
            '"body": "test message"',
            'https://api.github.com/repos/sme/frontend-test/issues/100/comments'
        ])
    }

    @Test
    void testCallWithPullRequestId() {
        githubPostPrComment(
            repo: 'frontend-test',
            message: 'test message',
            pullRequestId: '200'
        )

        assertMethodCalledTimes('withCredentials', 1)
        assertMethodCalledOnceWith('sh', [
            '"body": "test message"',
            'https://api.github.com/repos/theorchard/frontend-test/issues/200/comments'
        ])
    }
}
