name: Browser Extension Build

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

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build-shared-libraries:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Build and distribute shared libraries
        run: |
          cd ./shared
          chmod +x build-and-distribute.sh
          ./build-and-distribute.sh

      - name: Verify shared library distribution
        run: |
          # Check if files exist and were recently modified
          TARGET_DIRS=(
            "apps/browser-extension/src/utils/dist/shared/identity-generator"
            "apps/browser-extension/src/utils/dist/shared/password-generator"
            "apps/browser-extension/src/utils/dist/shared/models"
            "apps/browser-extension/src/utils/dist/shared/vault-sql"
          )

          for dir in "${TARGET_DIRS[@]}"; do
            if [ ! -d "$dir" ]; then
              echo "❌ Directory $dir does not exist"
              exit 1
            fi

            # Check if files were modified in the last 5 minutes
            find "$dir" -type f -mmin -5 | grep -q . || {
              echo "❌ Files in $dir were not recently modified"
              exit 1
            }
          done

          echo "✅ Shared library distribution verified"

  build-chrome-extension:
    needs: build-shared-libraries
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build Chrome Extension
        uses: ./.github/actions/build-browser-extension
        with:
          browser: chrome

  build-firefox-extension:
    needs: build-shared-libraries
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build Firefox Extension
        uses: ./.github/actions/build-browser-extension
        with:
          browser: firefox

  build-edge-extension:
    needs: build-shared-libraries
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build Edge Extension
        uses: ./.github/actions/build-browser-extension
        with:
          browser: edge
