name: Deploy Storybook to Cloudflare Workers
permissions:
  contents: read
  pull-requests: write
  issues: write
on:
  push:
    branches:
      - main
    paths:
      - 'unraid-ui/**'
  pull_request:
    paths:
      - 'unraid-ui/**'
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy Storybook
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - uses: pnpm/action-setup@v4
        name: Install pnpm
        with:
          run_install: false

      - name: Cache APT Packages
        uses: awalsh128/cache-apt-pkgs-action@v1.4.3
        with:
          packages: bash procps python3 libvirt-dev jq zstd git build-essential libvirt-daemon-system
          version: 1.0

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Build Storybook
        run: |
          cd unraid-ui
          pnpm build-storybook

      - name: Deploy to Cloudflare Workers (Staging)
        id: deploy_staging
        if: github.event_name == 'pull_request'
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_DEPLOY_TOKEN }}
          command: deploy --env staging
          workingDirectory: unraid-ui

      - name: Deploy to Cloudflare Workers (Production)
        if: github.ref == 'refs/heads/main' && github.event_name == 'push'
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_DEPLOY_TOKEN }}
          command: deploy
          workingDirectory: unraid-ui

      - name: Comment PR with deployment URL
        if: github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `🚀 Storybook has been deployed to staging: ${{ steps.deploy_staging.outputs['deployment-url'] }}`
            }) 