import groovy.transform.Field
import com.sonymusic.Utils

@Field GRAPHQL_URL ='https://grassproxy.pullrequests.qaorch.com/graphql-router/graphql'

def call(Map args) {
    def params = Utils.validateParams('suiteAppDeployPrInstance', args, [
        appName: [type: String, required: true],
        envVars: [type: Map, required: false, defaultValue: [:]],
        scriptNames: [type: List, itemType: String, required: false, defaultValue: null],
        pullRequestId: [type: String, required: false, defaultValue: env.CHANGE_ID],
        cdnUrl: [type: String, required: false, defaultValue: 'https://qa-cdn.theorchard.io'],
        bucket: [type: String, required: false],
        detectPackageManager: [type: Boolean, required: false, defaultValue: false]
    ])

    assert params.pullRequestId: 'suiteAppDeployPrInstance: Failed to determine the PR id, please make sure you are running in a PR branch.'

    // When a bucket is provided, use it as the CDN URL, since the bucket will always be named the exact FQDN
    // All internal SPAs expect the assets to be served from the same URL as well and do not use the shared CDN
    def resolvedCdnUrl = params.bucket ? "https://${params.bucket}" : params.cdnUrl
    def publicPath = "${resolvedCdnUrl}/${params.appName}/prs/${params.pullRequestId}/"
    def priDomain = env.PRI_DOMAIN ?: "${params.appName}-${params.pullRequestId}.pullrequests.qaorch.com"
    def defaultEnvVars = [
        GRAPHQL_URL: GRAPHQL_URL,
        CDN_URL: resolvedCdnUrl,
        PUBLIC_PATH: publicPath,
        AUTH0_REDIRECT_URI: "https://pullrequests.qaorch.com/auth0Redirect?to=${priDomain}"
    ]

    def resolvedScriptNames = params.scriptNames ?: ["frontend build --public-path ${publicPath}"]

    if(!params.scriptNames && params.envVars['POEDITOR_PROJECT_ID'])
        resolvedScriptNames = ["frontend i18n:download"] + resolvedScriptNames

    suiteAppBuild([
        env: 'qa',
        envVars: defaultEnvVars + params.envVars,
        scriptNames: resolvedScriptNames,
        detectPackageManager: params.detectPackageManager
    ])

    def publishArgs = [
        env: 'qa',
        appName: params.appName,
        subpath: "prs/${params.pullRequestId}"
    ]
    if (params.bucket) publishArgs.bucket = params.bucket
    suiteAppPublish(publishArgs)

    githubPostPrComment(
        repo: params.appName,
        message: "🚀 PR-Instance successfully deployed to: https://${priDomain}"
    )
}
