pipeline {
    agent any

    parameters {
        booleanParam(
            name: 'FORCE_BUILD_ALL',
            defaultValue: false,
            description: '强制构建所有镜像'
        )
    }

    environment {
        IMAGE_PREFIX = "im"
        IMAGE_TAG = "${BUILD_NUMBER}"
        DOCKER_BUILDKIT = "1"
        REGISTRY = ""
    }

    stages {
        stage('拉取代码') {
            steps {
                checkout scm
            }
        }

        stage('检测变更') {
            steps {
                script {
                    if (params.FORCE_BUILD_ALL || env.BUILD_NUMBER == '1') {
                        env.BUILD_ALL = "true"
                        env.CHANGED_FILES = "FIRST_BUILD"
                        echo "首次构建或手动强制构建，构建全部镜像"
                    } else {
                        env.BUILD_ALL = "false"

                        env.CHANGED_FILES = sh(
                            script: '''
                                git diff --name-only HEAD~1 HEAD
                            ''',
                            returnStdout: true
                        ).trim()

                        echo "变更文件："
                        echo env.CHANGED_FILES
                    }
                }
            }
        }

        stage('构建镜像') {
            steps {
                script {
                    def services = [
                        [
                            name: 'connector-service',
                            dockerfile: 'ConnectorService/Dockerfile',
                            image: 'connector-service',
                            paths: [
                                'ConnectorService/',
                                'IM.Commons/',
                                'IM.InitCommon/',
                                'IM.Protocols/'
                            ]
                        ],
                        [
                            name: 'user-service',
                            dockerfile: 'User.WebApi/Dockerfile',
                            image: 'user-service',
                            paths: [
                                'User.WebApi/',
                                'User.Domain/',
                                'User.Infrastructure/',
                                'DomainCommons/',
                                'Infrastructure/',
                                'IM.ASPNETCore/',
                                'IM.Commons/',
                                'IM.InitCommon/',
                                'IM.Jwt/',
                                'IM.Protocols/'
                            ]
                        ],
                        [
                            name: 'contact-service',
                            dockerfile: 'ContactService.WebApi/Dockerfile',
                            image: 'contact-service',
                            paths: [
                                'ContactService.WebApi/',
                                'ContactService.Domain/',
                                'ContactService.Infrastructure/',
                                'DomainCommons/',
                                'Infrastructure/',
                                'IM.ASPNETCore/',
                                'IM.Commons/',
                                'IM.InitCommon/',
                                'IM.Jwt/',
                                'IM.Protocols/'
                            ]
                        ],
                        [
                            name: 'group-service',
                            dockerfile: 'GroupService.WebApi/Dockerfile',
                            image: 'group-service',
                            paths: [
                                'GroupService.WebApi/',
                                'GroupService.Domain/',
                                'GroupService.Infrastructure/',
                                'DomainCommons/',
                                'Infrastructure/',
                                'IM.ASPNETCore/',
                                'IM.Commons/',
                                'IM.InitCommon/',
                                'IM.Jwt/',
                                'IM.Protocols/'
                            ]
                        ],
                        [
                            name: 'message-service',
                            dockerfile: 'MessageService.WebApi/Dockerfile',
                            image: 'message-service',
                            paths: [
                                'MessageService.WebApi/',
                                'MessageService.Domain/',
                                'MessageService.Infrastructure/',
                                'DomainCommons/',
                                'Infrastructure/',
                                'IM.ASPNETCore/',
                                'IM.Commons/',
                                'IM.InitCommon/',
                                'IM.Jwt/',
                                'IM.Protocols/'
                            ]
                        ]
                    ]

                    def changedFiles = env.CHANGED_FILES.split("\\n") as List

                    services.each { svc ->
                        def needBuild = env.BUILD_ALL == "true" || changedFiles.any { file ->
                            svc.paths.any { path ->
                                file.startsWith(path)
                            }
                        }

                        if (needBuild) {
                            def imageName = "${IMAGE_PREFIX}-${svc.image}:${IMAGE_TAG}"
                            def latestName = "${IMAGE_PREFIX}-${svc.image}:latest"

                            echo "开始构建镜像：${imageName}"

                            sh """
                                docker build \
                                  -t ${imageName} \
                                  -t ${latestName} \
                                  -f ${svc.dockerfile} .
                            """
                        } else {
                            echo "跳过构建：${svc.name}，没有相关代码变更"
                        }
                    }
                }
            }
        }
    }
}