---
name: CI Build

on:
  push:
    branches:
      - "**"
    paths-ignore:
      - "**/*.md"
      - "LICENSE"
  workflow_dispatch:
  schedule:
    - cron: "0 0 * * 1"

jobs:
  format:
    name: Rust Format Check
    runs-on: ubuntu-latest

    permissions:
      contents: read

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Rust Toolchain setup
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt

      - name: Format Check
        uses: mbrobbel/rustfmt-check@master
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

  clippy:
    name: Rust Clippy Check
    runs-on: ubuntu-latest

    permissions:
      contents: read
      security-events: write
      actions: read

    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Rust Toolchain setup
        uses: dtolnay/rust-toolchain@stable
        with:
          components: cargo, clippy

      - name: Run rust-clippy
        run: cargo clippy --all-features
        continue-on-error: true

  upload:
    name: Upload to Cloudflare
    runs-on: ubuntu-latest
    needs: [format, clippy]

    permissions:
      contents: read

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Rust Toolchain setup
        uses: dtolnay/rust-toolchain@stable
        with:
          target: wasm32-unknown-unknown

      - name: Setup Node
        uses: actions/setup-node@v6

      - name: Wrangler setup
        run: npm install -g wrangler

      - name: Build wasm and upload
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK_URL }}
        run: |
          wrangler versions upload --name=cookie-worker
          export WORKER_VERSION=$(wrangler versions list --name=cookie-worker --json | jq -r '.[-1].id')
          echo "cookie-worker uploaded as $WORKER_VERSION, to deploy this version run:\n \`wrangler versions deploy --name=cookie-worker --version-id=$WORKER_VERSION --yes\`"
