# 教学示例：先完成 CI，再生成可追溯的 Docker 交付制品。
# 它不包含真实服务器部署；没有目标环境、密钥治理、回滚和 smoke test 时，不能宣称生产 CD。
name: w03-ci-delivery

on:
  pull_request:
  push:
    branches: [main]
  workflow_dispatch:

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: backend
    steps:
      - name: Checkout the exact commit
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip
          cache-dependency-path: backend/requirements.txt

      - name: Install dependencies
        run: python -m pip install -r requirements.txt

      - name: Run unit and contract tests
        run: python -m pytest tests/unit tests/contract -q

  build-image:
    # 测试失败时，不生成可交付候选镜像。
    needs: test
    # PR 只验证测试；合入 main 或手工触发时才构建归档，减少无意义资源消耗。
    if: github.event_name != 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout the same commit
        uses: actions/checkout@v4

      - name: Build image tagged by commit SHA
        run: docker build --tag w03-commerce:${{ github.sha }} ./backend

      - name: Save image as a delivery artifact
        run: docker save w03-commerce:${{ github.sha }} --output w03-commerce-image.tar

      - name: Upload short-lived teaching artifact
        uses: actions/upload-artifact@v4
        with:
          name: w03-commerce-${{ github.sha }}
          path: w03-commerce-image.tar
          if-no-files-found: error
          retention-days: 3

# 真正的 deploy job 暂不提供可复制答案。
# 它必须在 Product Owner/教师冻结目标环境、镜像仓库、Secret、审批、迁移、回滚和 smoke test 后设计。
