pipeline {
    agent any

    environment {
        REGISTRY_URL    = "registry.pablotj.com"
        USER            = "andromeda"
        PASS            = credentials('docker-registry-password')
    }

    stages {
        stage('Prepare Workspace & Checkout') {
            steps {
                echo "Cleaning workspace"
                deleteDir()
            }
        }


        stage('Checkout') {
            steps {
                echo "Checking out repo..."
                checkout scm
            }
        }

        stage('Load Environment') {
            steps {
                echo "Loading .env secret from Jenkins..."
                withCredentials([file(credentialsId: 'env', variable: 'SECRET_ENV')]) {
                    sh 'cp $SECRET_ENV .env'
                }
            }
        }

        stage('Build and Tag Docker Image') {
            steps {
                echo "Building Docker image..."
                sh '''
                   make build
                   make tag
                '''
            }
        }

        stage('ush Docker Image') {
            steps {
                echo "Tagging and pushing Docker image to registry..."
                sh '''
                    echo $PASS | docker login ${REGISTRY_URL} -u ${USER} --password-stdin
                    make push
                '''
            }
        }

        stage('Deploy Docker Container') {
            steps {
                echo "Stopping old container and running new container..."
                sh '''
                    make stop
                    make run
                '''
            }
        }
    }

    post {
        success {
            echo "✅ Deployment completed successfully!"
        }
        failure {
            echo "❌ Pipeline failed!"
        }
        always {
            deleteDir()
        }
    }
}