name: devsecops-stage-pipeline-modernized

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

permissions:
  contents: read

jobs:
  lint-and-unit:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4
      - name: Set up language runtime
        uses: actions/setup-node@v4
        with:
          node-version: '22'
      - name: Install dependencies
        run: npm ci
      - name: Lint
        run: npm run lint
      - name: Unit tests
        run: npm test -- --ci

  secrets-and-sast:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - uses: actions/checkout@v4
      - name: Run secrets scan
        run: ./scripts/scan-secrets.sh
      - name: Run fast SAST
        run: ./scripts/run-sast.sh

  build-image:
    runs-on: ubuntu-latest
    needs: [lint-and-unit, secrets-and-sast]
    permissions:
      contents: read
      packages: write
      attestations: write
      id-token: write
    outputs:
      image_digest: ${{ steps.build.outputs.digest }}
    steps:
      - uses: actions/checkout@v4
      - name: Build container image
        id: build
        run: |
          ./scripts/build-image.sh
          echo "digest=sha256:replace_me" >> "$GITHUB_OUTPUT"
      - name: Generate SBOM
        run: ./scripts/generate-sbom.sh
      - name: Run image scan
        run: ./scripts/scan-image.sh
      - name: Create provenance / attestation
        run: ./scripts/create-attestation.sh

  preview-deploy:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    needs: [build-image]
    permissions:
      contents: read
      id-token: write
    environment:
      name: preview
    steps:
      - uses: actions/checkout@v4
      - name: Authenticate with cloud using OIDC
        run: ./scripts/cloud-oidc-login.sh
      - name: Deploy preview environment
        run: ./scripts/deploy-preview.sh
      - name: Run smoke and authz tests
        run: ./scripts/smoke-and-authz-tests.sh

  release-evidence:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    needs: [build-image]
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
      - name: Persist release metadata
        run: ./scripts/persist-release-evidence.sh

  deploy-production:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    needs: [build-image, release-evidence]
    permissions:
      contents: read
      id-token: write
    environment:
      name: production
      url: https://app.example.com
    concurrency:
      group: production
      cancel-in-progress: false
    steps:
      - uses: actions/checkout@v4
      - name: Authenticate with cloud using OIDC
        run: ./scripts/cloud-oidc-login.sh
      - name: Verify artifact digest / signature
        run: ./scripts/verify-artifact-trust.sh
      - name: Deploy production
        run: ./scripts/deploy-production.sh
