name: build-mailadler-macos

on:
  workflow_dispatch:
  push:
    branches: [main, master]
    paths:
      - 'src/**'
      - 'CMakeLists.txt'
      - '.github/workflows/build-macos.yml'
  pull_request:
    branches: [main, master]

env:
  QT_VERSION: 6.6.3

jobs:
  build:
    runs-on: macos-14  # Apple Silicon

    steps:
      - uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Install Qt
        uses: jurplel/install-qt-action@v4
        with:
          version: ${{ env.QT_VERSION }}
          modules: 'qtwebsockets'
          cache: true

      - name: Install dependencies
        run: |
          brew install ninja openssl@3

      - name: Prepare version
        run: |
          VERSION=$(date +"%y.%-m.%-d-%H%M")
          echo "VERSION=$VERSION" >> $GITHUB_ENV

      - name: Configure
        run: |
          cmake -B build -G Ninja \
            -DCMAKE_BUILD_TYPE=Release \
            -DCMAKE_PREFIX_PATH="$Qt6_DIR" \
            -DOPENSSL_ROOT_DIR="$(brew --prefix openssl@3)"

      - name: Build
        run: cmake --build build --parallel

      - name: Package DMG
        run: |
          cd build
          # Create app bundle structure
          mkdir -p mailadler.app/Contents/MacOS
          mkdir -p mailadler.app/Contents/Resources
          cp src/mailadler mailadler.app/Contents/MacOS/ 2>/dev/null || cp src/mailadler.app/Contents/MacOS/mailadler mailadler.app/Contents/MacOS/ 2>/dev/null || true
          
          # Deploy Qt frameworks
          $Qt6_DIR/bin/macdeployqt mailadler.app -dmg 2>/dev/null || true
          
          # Rename DMG
          mv mailadler.dmg ../mailadler-macos-${{ env.VERSION }}.dmg 2>/dev/null || \
          hdiutil create -volname "mailadler" -srcfolder mailadler.app -ov -format UDZO ../mailadler-macos-${{ env.VERSION }}.dmg 2>/dev/null || \
          echo "DMG creation skipped"

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: macos-dmg
          path: mailadler-macos-*.dmg
          if-no-files-found: ignore

      - name: Upload to release (on tag)
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v1
        with:
          files: mailadler-macos-*.dmg
