pipeline {
    agent {
        label "docker-agent-dsrv02"
    }

    environment {
        DOCKER_REGISTRY = 'gitea.postio.pl'
        IMAGE_NAME = 'oxdr-swagger-ui'
    }

    parameters {
        string(name: 'BUILD_ID', defaultValue: 'latest', description: 'Image tag / build identifier')
    }

    stages {
        stage('Checkout') {
            steps {
                git branch: 'main', credentialsId: 'postio-bot-gitea', url: 'https://gitea.postio.pl/public/microservice-repository.git'
            }
        }

        stage('Generate Swagger Docs') {
            agent {
                docker {
                    image 'bufbuild/buf:latest'
                    reuseNode true
                }
            }
            steps {
                dir("${env.WORKSPACE}") {
                    sh '''
                        echo "Generating Swagger documentation..."
                        buf generate

                        echo "Converting OpenAPI V2 to V3..."
                        python3 scripts/process_openapiv2.py
                    '''
                }
            }
        }

        stage('Build Docker Image') {
            steps {
                sh '''
                    echo "Building Docker image..."
                    docker build -t ${DOCKER_REGISTRY}/${IMAGE_NAME}:${BUILD_ID} \
                        -f deployments/docker/Dockerfile deployments/docker/
                '''
            }
        }

        stage('Push Docker Image') {
            steps {
                withCredentials([usernamePassword(
                    credentialsId: 'postio-bot-gitea',
                    usernameVariable: 'DOCKER_USER',
                    passwordVariable: 'DOCKER_PASS'
                )]) {
                    sh '''
                        echo "Logging into Docker registry..."
                        echo $DOCKER_PASS | docker login ${DOCKER_REGISTRY} -u $DOCKER_USER --password-stdin

                        echo "Pushing Docker image..."
                        docker push ${DOCKER_REGISTRY}/${IMAGE_NAME}:${BUILD_ID}
                    '''
                }
            }
        }
    }

    post {
        failure {
            echo "Build failed. Check the console output for details."
        }
    }
}
