@Library('example-shared-lib@main') _

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

    environment {
        DOCKER_REGISTRY = 'gitea.postio.pl'
        IMAGE_NAME = 'public/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'
                    args '--entrypoint='
                    reuseNode true
                }
            }
            environment {
                BUF_CACHE_DIR="${env.WORKSPACE}/.cache"
            }
            steps {
                dir("${env.WORKSPACE}") {
                    echo "Generating Swagger documentation..."
                    sh "buf generate"
                }
            }
        }
        stage('Convert OpenAPI to v3') {
            agent {
                docker {
                    image 'python:3-bookworm'
                    reuseNode true
                }
            }
            steps {
                dir("${env.WORKSPACE}") {
                    echo "Converting OpenAPI V2 to V3..."
                    sh "python3 scripts/process_openapiv2.py"
                }
            }
        }

        stage('Build Docker Image') {
            steps {
                dockerBuild(
                    imageName: "${IMAGE_NAME}:${params.BUILD_ID}",
                    dockerfile: "deployments/docker/Dockerfile",
                    context: "deployments/docker"
                )
            }
        }

        stage('Push Docker Image') {
            steps {
                dockerPush(
                    imageName: "${IMAGE_NAME}:${params.BUILD_ID}",
                    registry: "${DOCKER_REGISTRY}",
                    credentialsId: "postio-bot-gitea"
                )
            }
        }
    }

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