pipeline {
    agent any

    environment {
        BACKUP_DIR = './backup'
    }

    stages {
        stage('Checkout') {
    steps {
        checkout scm
    }
}

        stage('Setup') {
            steps {
                script {
                    BRANCH_NAME = env.BRANCH_NAME.split('/')[-1] // Extract branch name

                    switch(BRANCH_NAME) {
                        case "test08":
                            env.BASE_URL = "https://test08.bizgaze.com/Account/Import/"
                            env.AUTH_TOKEN = "6884972896664f4582e08f7f93da953d"
                            break
                        case "qaanwi":
                            env.BASE_URL = "https://qa.anwisystems.com/Account/Import/"
                            env.AUTH_TOKEN = "541c35d52a7b449f956175992619ed3a"
                            break
                        default:
                            error "Unknown branch: ${BRANCH_NAME}. Exiting."
                    }
                }
            }
        }

        stage('Process XML files') {
            steps {
                script {
                    process_folder('./app', 'app')
                    process_folder('./report', 'report')
                    process_folder('./form', 'form')
                    commitChanges()
                }
            }
        }
    }
}

def process_folder(folder, import_type) {
    import_url = "${env.BASE_URL}${import_type}"
    backup_folder = "${env.BACKUP_DIR}/${import_type}"

    sh "mkdir -p ${backup_folder}"

    // Use find command to get XML files and avoid error if none found
    def fileList = sh(script: "find ${folder} -name '*.xml' || echo ''", returnStdout: true).trim().split('\n')

    // Remove any empty strings from the list
    fileList = fileList.findAll { it != '' }

    // Check if we found any files
    if (fileList.size() == 0) {
        echo "No XML files found in ${folder}."
        return
    }

    echo "Detected files: ${fileList.join(', ')}"

    for(file in fileList) {
        def response = sh(script: """
    curl --location --request POST "${import_url}" \
    --header 'Authorization: stat ${env.AUTH_TOKEN}' \
    --form "=@${file}"
    """, returnStdout: true).trim()

        if(response != '') { // or other success condition
            sh "mv \"${file}\" \"${backup_folder}/\""
            echo "API Response: ${response}"
        } else {
            echo "Error while uploading ${file} to ${import_url}"
        }
    }
}

def commitChanges() {
    // Configure Git
    sh """
        git config user.email "jenkins@bizgaze.in"
        git config user.name "jenkinstest"
    """

    // Check for changes
    sh """
        git checkout ${env.BRANCH_NAME}
        git pull origin ${env.BRANCH_NAME}
        git add .
        git commit -m "Moved processed XML files to backup"
        git push --force https://jenkinstest:Bizgaze123@code.bizgaze.com/devops.bizgaze/imports.git ${env.BRANCH_NAME}
    """
}

