name: Build & Cache Web App

on:
  workflow_dispatch:
    inputs:
      e2e_testing_mode:
        description: "Set E2E Testing Mode"
        required: false
        default: "0"

inputs:
  turbo_token:
    description: "Turborepo token"
    required: false
  turbo_team:
    description: "Turborepo team"
    required: false

runs:
  using: "composite"
  steps:
    - name: Checkout repo
      uses: actions/checkout@v3

    - uses: ./.github/actions/dangerous-git-checkout

    - name: Cache Build
      uses: actions/cache@v3
      id: cache-build
      env:
        cache-name: prod-build
        key-1: ${{ hashFiles('pnpm-lock.yaml') }}
        key-2: ${{ hashFiles('apps/**/**.[jt]s', 'apps/**/**.[jt]sx', 'packages/**/**.[jt]s', 'packages/**/**.[jt]sx', '!**/node_modules') }}
      with:
        path: |
          ${{ github.workspace }}/apps/web/.next
          **/.turbo/**
          **/dist/**
        key: ${{ runner.os }}-${{ env.cache-name }}-${{ env.key-1 }}-${{ env.key-2 }}

    - name: Set Cache Hit Status
      run: echo "cache-hit=${{ steps.cache-build.outputs.cache-hit }}" >> "$GITHUB_OUTPUT"
      shell: bash

    - name: Setup Node.js 20.x
      uses: actions/setup-node@v3
      with:
        node-version: 20.x
      if: steps.cache-build.outputs.cache-hit != 'true'

    - name: Install pnpm
      uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0
      if: steps.cache-build.outputs.cache-hit != 'true'

    - name: Install dependencies
      run: pnpm install --config.platform=linux --config.architecture=x64
      if: steps.cache-build.outputs.cache-hit != 'true'
      shell: bash

    - name: create .env
      run: cp .env.example .env
      shell: bash

    - name: Fill ENCRYPTION_KEY, ENTERPRISE_LICENSE_KEY and E2E_TESTING in .env
      run: |
        RANDOM_KEY=$(openssl rand -hex 32)
        sed -i "s/ENCRYPTION_KEY=.*/ENCRYPTION_KEY=${RANDOM_KEY}/" .env
        echo "E2E_TESTING=${{ inputs.e2e_testing_mode }}" >> .env
      shell: bash

    - run: |
        pnpm build --filter=@formbricks/web...
      if: steps.cache-build.outputs.cache-hit != 'true'
      shell: bash
      env:
        TURBO_TOKEN: ${{ inputs.turbo_token }}
        TURBO_TEAM: ${{ inputs.turbo_team }}
