pipeline {
    agent any

    parameters {
        // This MUST match the parameter name you defined in the Jenkins UI
        string(name: 'SOURCE_TAG', defaultValue: 'latest', description: 'The local image tag (BUILD_ID) to push.')
    }

    environment {
        // Tag images with the build number so they are unique
        VUE_CONTAINER_NAME = "chore-app-frontend"
        FLASK_CONTAINER_NAME = "chore-app-backend"

        REGISTRY = "172.17.0.1:5900" // Your Docker Registry
        REPO_FRONTEND = "${REGISTRY}/${VUE_CONTAINER_NAME}"
        REPO_BACKEND = "${REGISTRY}/${FLASK_CONTAINER_NAME}"

        // Use a new tag (e.g., 'production') for the permanent repo
        NEW_PERM_TAG = "production"
    }

    stages {
        stage('Pull Local Images') {
            steps {
                // Ensure the source images are available locally
                sh "docker pull ${VUE_CONTAINER_NAME}:${params.SOURCE_TAG} || true"
                sh "docker pull ${FLASK_CONTAINER_NAME}:${params.SOURCE_TAG} || true"
            }
        }

        stage('Tag and Push Known Good') {
            steps {
                echo "Promoting image tag ${params.SOURCE_TAG} to ${NEW_PERM_TAG} on ${REGISTRY}"

                // 1. Tag the specific local image with the permanent tag
                sh "docker tag ${VUE_CONTAINER_NAME}:${params.SOURCE_TAG} ${REPO_FRONTEND}:${NEW_PERM_TAG}"
                sh "docker tag ${FLASK_CONTAINER_NAME}:${params.SOURCE_TAG} ${REPO_BACKEND}:${NEW_PERM_TAG}"

                // 2. Push the newly tagged images
                sh "docker push ${REPO_FRONTEND}:${NEW_PERM_TAG}"
                sh "docker push ${REPO_BACKEND}:${NEW_PERM_TAG}"

                echo "Images pushed successfully. New permanent tag is ${NEW_PERM_TAG}."
            }
        }
    }
}
