pipeline {
    agent any

    parameters {
        string(
                name: 'BRANCH',
                defaultValue: 'dev',
                description: 'Ветка для деплоя'
        )
        string(
                name: 'SERVER',
                defaultValue: '92.242.61.23',
                description: 'Сервер для деплоя'
        )
    }

    stages {
        stage('Git pull') {
            steps {
                cleanWs()
                script {
                    checkout([
                            $class: 'GitSCM',
                            branches: [[name: params.BRANCH]],
                            userRemoteConfigs: [[
                                                        url: 'https://code.3err0.ru/backdev/no-copy.git',
                                                        credentialsId: 'nx-jen'
                                                ]]
                    ])
                }
            }
        }

        stage('Deploy with docker-compose') {
            steps {
                script {
                    def buildTime = sh(script: "TZ='Asia/Novosibirsk' date '+%d-%m-%Y %H:%M:%S'", returnStdout: true).trim()
                    withCredentials([
                            usernamePassword(
                                    credentialsId: 'server-root-password',
                                    usernameVariable: 'SSH_USER',
                                    passwordVariable: 'SSH_PASS'
                            ),
                            string(credentialsId: 'DB_USER', variable: 'DB_USER'),
                            string(credentialsId: 'DB_PASSWORD', variable: 'DB_PASSWORD')
                    ]) {
                        sh """
                        echo "Deploying branch: ${params.BRANCH}"

                        echo "Copying files to server..."
                        sshpass -p '$SSH_PASS' ssh -o StrictHostKeyChecking=no $SSH_USER@$SERVER "mkdir -p /opt/deployments/${params.BRANCH}"

                        sshpass -p '$SSH_PASS' rsync -av --delete \\
                          --exclude=.git \\
                          --exclude=.gradle \\
                          --exclude=build \\
                          --exclude=**/build \\
                          --exclude=.idea \\
                          --exclude=out \\
                          . $SSH_USER@$SERVER:/opt/deployments/${params.BRANCH}/

                        sshpass -p '$SSH_PASS' ssh -o StrictHostKeyChecking=no $SSH_USER@$SERVER "
                            cd /opt/deployments/${params.BRANCH}

                            echo '1. Остановка старого приложения...'
                            docker stop app-backend 2>/dev/null || echo 'Контейнер не найден'
                            docker rm app-backend 2>/dev/null || echo 'Контейнер не найден'

                            echo '2. Удаление старых образов...'
                            docker images --filter 'reference=*app*' -q | xargs -r docker rmi -f 2>/dev/null || echo 'Нет образов для удаления'

                            echo '3. Создание сети если нужно...'
                            docker network create app-network 2>/dev/null || echo 'Сеть уже существует'

                            echo '4. Запуск инфраструктуры...'
                            docker-compose up -d db storage

                            echo '5. Ожидание PostgreSQL...'
                            sleep 10

                            echo '6. Сборка нового образа приложения...'
                            docker build --no-cache -t app-backend:latest .

                            echo '7. Запуск приложения...'
                            docker run -d \\
                              --name app-backend \\
                              --network app-network \\
                              --network-alias app \\
                              -p 80:8080 \\
                              -v uploads_data:/data/uploads:rw \\
                              -e POSTGRES_DB=no_copy_ \\
                              -e POSTGRES_USER=$DB_USER \\
                              -e POSTGRES_PASSWORD=$DB_PASSWORD \\
                              -e POSTGRES_PORT=5432 \\
                              -e POSTGRES_HOST=db \\
                              -e BUILD_TIME_BACK='${buildTime}' \\
                              --restart unless-stopped \\
                              app-backend:latest

                            echo '8. Запуск мониторинга...'
                            docker-compose up -d grafana prometheus loki tempo alloy

                            echo '9. Проверка...'
                            sleep 5

                            echo 'Статус контейнеров:'
                            docker ps --format 'table {{.Names}}\\t{{.Image}}\\t{{.Status}}'

                            echo '10. Проверка health...'
                            if curl -s -f http://localhost:80/health > /dev/null 2>&1; then
                                echo 'Приложение работает'
                                echo 'URL: http://${params.SERVER}:80'
                            else
                                echo 'Проверка health не удалась'
                                docker logs app-backend --tail=20
                            fi
                        "
                        """
                    }
                }
            }
        }
    }

    post {
        success {
            echo "Deployment successful"
            echo "Application URL: http://${params.SERVER}:80"
        }
        failure {
            echo "Deployment failed for branch ${params.BRANCH}"
        }
        always {
            echo "Deployment process finished"
        }
    }
}
