name: Build and Deploy AdminApi

on:
  push:
    branches:
      - dev

jobs:
  build-and-deploy:
    runs-on: host
    steps:
      - name: Checkout code
        run: |
          cd /opt/deploy/adminapi || mkdir -p /opt/deploy/adminapi
          cd /opt/deploy/adminapi

          # 如果已有仓库就 pull，否则 clone
          if [ -d ".git" ]; then
            git fetch origin dev
            git reset --hard origin/dev
            git submodule update --init --recursive
          else
            git clone --branch dev ssh://git@git.laosankeji.com:2222/msumshk/TakeoutSaaS.AdminApi.git .
            git submodule init
            git config submodule.TakeoutSaaS.BuildingBlocks.url ssh://git@git.laosankeji.com:2222/msumshk/TakeoutSaaS.BuildingBlocks.git
            git config submodule.TakeoutSaaS.Docs.url ssh://git@git.laosankeji.com:2222/msumshk/TakeoutSaaS.Docs.git
            git submodule update
          fi

      - name: Build on host
        run: |
          cd /opt/deploy/adminapi
          dotnet restore src/Api/TakeoutSaaS.AdminApi/TakeoutSaaS.AdminApi.csproj
          dotnet publish src/Api/TakeoutSaaS.AdminApi/TakeoutSaaS.AdminApi.csproj -c Release -o /opt/deploy/adminapi/publish --no-restore

      - name: Build Docker image
        run: |
          cd /opt/deploy/adminapi
          docker build -t takeoutsaas-adminapi:latest -f src/Api/TakeoutSaaS.AdminApi/Dockerfile .

      - name: Deploy container
        run: |
          docker stop adminapi || true
          docker rm adminapi || true
          docker run -d \
            --name adminapi \
            --restart unless-stopped \
            -p 7801:7801 \
            -e ASPNETCORE_ENVIRONMENT=Production \
            takeoutsaas-adminapi:latest

      - name: Clean up old images
        run: |
          docker image prune -f
