steps:
  audit_dependencies:
    image: node:20
    commands:
      - npm install --package-lock-only
      - npm audit --audit-level=moderate --json > audit-result.json 2>&1 || echo "Audit completed"
      - npm audit --audit-level=moderate > audit-output.txt 2>&1 || echo "Audit completed"
    when:
      - branch: main
        event: push

  discord_notify_audit:
    image: alpine:latest
    environment:
      DISCORD_WEBHOOK:
        from_secret: discord_webhook
    commands:
      - apk add --no-cache curl jq
      - |
        if [ -f audit-result.json ]; then
          TOTAL=$(jq -r '.metadata.vulnerabilities.total // 0' audit-result.json 2>/dev/null || echo "0")
          CRITICAL=$(jq -r '.metadata.vulnerabilities.critical // 0' audit-result.json 2>/dev/null || echo "0")
          HIGH=$(jq -r '.metadata.vulnerabilities.high // 0' audit-result.json 2>/dev/null || echo "0")
          MODERATE=$(jq -r '.metadata.vulnerabilities.moderate // 0' audit-result.json 2>/dev/null || echo "0")
          LOW=$(jq -r '.metadata.vulnerabilities.low // 0' audit-result.json 2>/dev/null || echo "0")

          if [ "$CRITICAL" -gt 0 ] || [ "$HIGH" -gt 0 ] || [ "$MODERATE" -gt 0 ]; then
            COLOR=16744448
            STATUS="⚠️ Vulnerabilities Found"
          else
            COLOR=3066993
            STATUS="✅ No Vulnerabilities"
          fi

          if [ -f audit-output.txt ]; then
            VULNS=$(head -50 audit-output.txt | tail -40 || echo "No details")
          else
            VULNS="No audit output available"
          fi

          printf '%s' "$VULNS" > /tmp/vulns.txt

          PAYLOAD=$(jq -n \
            --arg title "🔒 Security Audit - Build #${CI_BUILD_NUMBER}" \
            --arg status "$STATUS" \
            --arg total "$TOTAL" \
            --arg critical "$CRITICAL" \
            --arg high "$HIGH" \
            --arg moderate "$MODERATE" \
            --arg low "$LOW" \
            --arg commit "${CI_COMMIT_SHA:0:7}" \
            --rawfile details /tmp/vulns.txt \
            --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" \
            --argjson color "$COLOR" \
            '{
              embeds: [{
                title: $title,
                description: $status,
                color: $color,
                fields: [
                  { name: "Total", value: $total, inline: true },
                  { name: "Critical", value: $critical, inline: true },
                  { name: "High", value: $high, inline: true },
                  { name: "Moderate", value: $moderate, inline: true },
                  { name: "Low", value: $low, inline: true },
                  { name: "Commit", value: ("`" + $commit + "`"), inline: true },
                  { name: "Details", value: ("```\n" + ($details[:800]) + (if ($details | length) > 800 then "\n... (truncated)" else "" end) + "\n```"), inline: false }
                ],
                timestamp: $timestamp
              }]
            }')

          curl -H "Content-Type: application/json" -X POST \
            -d "$PAYLOAD" "$DISCORD_WEBHOOK"
        else
          echo "No audit results found - listing workspace files:"
          ls -la
        fi
    when:
      - branch: main
        event: push

  deploy_frontend:
    image: node:20
    environment:
      FLY_API_TOKEN:
        from_secret: FLY_API_TOKEN
    commands:
      - curl -L https://fly.io/install.sh | sh
      - export PATH="$HOME/.fly/bin:$PATH"
      - flyctl deploy --config fly.toml --app gallus-pub --remote-only
    when:
      - branch: main
        event: push

  notify_success:
    image: alpine:latest
    environment:
      DISCORD_WEBHOOK:
        from_secret: discord_webhook
    commands:
      - apk add --no-cache curl jq
      - |
        # Schreibe Commit-Message in Datei (sicher gegen Shell-Sonderzeichen)
        printf '%s\n' "$CI_COMMIT_MESSAGE" > /tmp/commit_msg.txt

        PAYLOAD=$(cat /tmp/commit_msg.txt | jq -Rs \
          --arg title "✅ Build #${CI_BUILD_NUMBER} - Success" \
          --arg repo "${CI_REPO}" \
          --arg branch "${CI_COMMIT_BRANCH}" \
          --arg commit "${CI_COMMIT_SHA:0:7}" \
          --arg author "${CI_COMMIT_AUTHOR}" \
          --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" \
          '. as $message | {
            embeds: [{
              title: $title,
              description: "Build und Deployment erfolgreich abgeschlossen!",
              color: 3066993,
              fields: [
                { name: "Repository", value: $repo, inline: true },
                { name: "Branch", value: $branch, inline: true },
                { name: "Commit", value: ("`" + $commit + "`"), inline: true },
                { name: "Author", value: $author, inline: true },
                { name: "Commit Message", value: $message, inline: false }
              ],
              timestamp: $timestamp
            }]
          }')

        curl -H "Content-Type: application/json" -X POST \
          -d "$PAYLOAD" "$DISCORD_WEBHOOK"
    when:
      - branch: main
        event: push
        status: success

  notify_failure:
    image: alpine:latest
    environment:
      DISCORD_WEBHOOK:
        from_secret: discord_webhook
    commands:
      - apk add --no-cache curl jq
      - |
        # Schreibe Commit-Message in Datei (sicher gegen Shell-Sonderzeichen)
        printf '%s\n' "$CI_COMMIT_MESSAGE" > /tmp/commit_msg.txt

        PAYLOAD=$(cat /tmp/commit_msg.txt | jq -Rs \
          --arg title "❌ Build #${CI_BUILD_NUMBER} - Failure" \
          --arg repo "${CI_REPO}" \
          --arg branch "${CI_COMMIT_BRANCH}" \
          --arg commit "${CI_COMMIT_SHA:0:7}" \
          --arg author "${CI_COMMIT_AUTHOR}" \
          --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" \
          '. as $message | {
            embeds: [{
              title: $title,
              description: "Build oder Deployment ist fehlgeschlagen!",
              color: 15158332,
              fields: [
                { name: "Repository", value: $repo, inline: true },
                { name: "Branch", value: $branch, inline: true },
                { name: "Commit", value: ("`" + $commit + "`"), inline: true },
                { name: "Author", value: $author, inline: true },
                { name: "Commit Message", value: $message, inline: false }
              ],
              timestamp: $timestamp
            }]
          }')

        curl -H "Content-Type: application/json" -X POST \
          -d "$PAYLOAD" "$DISCORD_WEBHOOK"
    when:
      - branch: main
        event: push
        status: failure