package com.sonymusic

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

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

class GithubGetCommitPrsTest extends BaseGlobalVarTest {
    def githubGetCommitPrs
    def response = [
        [
            number: 123,
            title: 'Test PR 1'
        ],
        [
            number: 456,
            title: 'Test PR 2'
        ]
    ]

    @BeforeEach
    void setUp() {
        super.setUp()
        githubGetCommitPrs = loadScript('vars/githubGetCommitPrs.groovy')
        helper.registerAllowedMethod('withCredentials', [Map])
        helper.registerAllowedMethod('sh', [Map])
        helper.registerAllowedMethod('readJSON', [Map], {
            return response
        })
    }

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

    @Test
    void testCallSuccess() {
        def prs = githubGetCommitPrs(
            repo: 'test',
            commitSha: 'abc123'
        )

        assertMethodCalledOnceWith('withCredentials', '[GITHUB_TOKEN]')
        assertMethodCalledOnceWith('sh', [
            'curl -X GET -H "Authorization: token \${GITHUB_TOKEN}"',
            'https://api.github.com/repos/theorchard/test/commits/abc123/pulls'
        ])

        assertEquals(prs, response)
    }

    @Test
    void testCallWithOwner() {
        def prs = githubGetCommitPrs(
            repo: 'test',
            commitSha: 'abc123',
            owner: 'custom-owner'
        )

        assertMethodCalledOnceWith('withCredentials', '[GITHUB_TOKEN]')
        assertMethodCalledOnceWith('sh', [
            'curl -X GET -H "Authorization: token \${GITHUB_TOKEN}"',
            'https://api.github.com/repos/custom-owner/test/commits/abc123/pulls'
        ])

        assertEquals(prs, response)
    }

}
