pipeline {
    agent { label 'windows-host' }
    environment {
        DOTNET_CLI_TELEMETRY_OPTOUT = '1'
        JAVA_TOOL_OPTIONS = '-Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8'
    }
    stages {
		stage('Clean') {
			steps {
				bat 'if exist publish rmdir /s /q publish'
			}
		}

        stage('Build') {
			steps {
				bat 'chcp 65001 && dotnet publish Web.Api/Web.Api.csproj -c Release -o publish\\api'
				bat 'chcp 65001 && dotnet publish Admin/Admin.csproj -c Release -o publish\\admin'
			}
		}

        stage('Stop Services') {
            steps {
                bat 'chcp 65001 && sc.exe stop bitforum-Api || exit 0'
                bat 'chcp 65001 && sc.exe stop bitforum-Admin || exit 0'
				bat 'taskkill /F /IM Web.Api.exe 2>nul || exit 0'
                bat 'taskkill /F /IM Admin.exe 2>nul || exit 0'
                bat 'ping 127.0.0.1 -n 6 > nul'
            }
        }
        stage('Deploy API') {
            steps {
                bat 'chcp 65001 && robocopy publish\\api H:\\IIS\\bitforum-api\\sources /MIR /XF web.config restart.ps1 appsettings.Production.json /XD logs /NFL /NDL /NP & if %ERRORLEVEL% LEQ 7 exit /b 0'
            }
        }
        stage('Deploy Admin') {
            steps {
                bat 'chcp 65001 && robocopy publish\\admin H:\\IIS\\bitforum-admin\\sources /MIR /XF web.config restart.ps1 appsettings.Production.json /XD logs /NFL /NDL /NP & if %ERRORLEVEL% LEQ 7 exit /b 0'
            }
        }
        stage('Start Services') {
            steps {
                bat 'chcp 65001 && sc.exe start bitforum-Api'
                bat 'chcp 65001 && sc.exe start bitforum-Admin'
            }
        }
    }
    post {
        success { echo 'Backend deploy success!' }
        failure { echo 'Backend deploy failed!' }
    }
}