import com.sonymusic.ECRImage
import com.sonymusic.Utils

def call(Map args) {
    def params = Utils.validateParams('snowcli', args, [
        command  : [type: String, required: true],
        account  : [type: String, required: true],
        user     : [type: String, required: true],
        database : [type: String, required: true],
        schema   : [type: String, required: true],
        role     : [type: String, required: true],
        warehouse: [type: String, required: true],
        snowcliImage: [type: String, required: false, defaultValue: '086679231553.dkr.ecr.us-east-1.amazonaws.com/snowcli:latest'],
    ])

    if (!env.SNOWFLAKE_PRIVATE_KEY_RAW || !env.PRIVATE_KEY_PASSPHRASE) {
        throw new IllegalStateException("Environment variables SNOWFLAKE_PRIVATE_KEY_RAW and PRIVATE_KEY_PASSPHRASE must be set for authentication.")
    }

    ECRImage snowcliImage = ECRImage.fromString(params.snowcliImage)

    withEcr(registries: [[accountId: snowcliImage.accountId, region: snowcliImage.region]]) {
        sh """
            docker run \
              --rm \
              --pull always \
              -v \"\$(pwd):/workspace\" \
              -w /workspace \
              -e SNOWFLAKE_ACCOUNT=${params.account} \
              -e SNOWFLAKE_USER=${params.user} \
              -e SNOWFLAKE_DATABASE=${params.database} \
              -e SNOWFLAKE_SCHEMA=${params.schema} \
              -e SNOWFLAKE_ROLE=${params.role} \
              -e SNOWFLAKE_WAREHOUSE=${params.warehouse} \
              -e SNOWFLAKE_PRIVATE_KEY_RAW \
              -e PRIVATE_KEY_PASSPHRASE \
              -e SNOWFLAKE_AUTHENTICATOR=SNOWFLAKE_JWT \
              ${params.snowcliImage} \
              ${params.command} --temporary-connection
        """
    }
}
