name: iOS Build

on:
  push:
    branches:
      - master
      - main
      - 'feature/**'
      - 'release/**'
  pull_request:
    branches:
      - master
      - main
  workflow_dispatch:
    inputs:
      build_type:
        description: 'Build type'
        required: true
        default: 'debug'
        type: choice
        options:
          - debug
          - release

env:
  FLUTTER_VERSION: '3.24.0'
  XCODE_VERSION: '15.0'

jobs:
  build-ios:
    runs-on: macos-14
    timeout-minutes: 60

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Flutter
        uses: subosito/flutter-action@v2
        with:
          flutter-version: ${{ env.FLUTTER_VERSION }}
          channel: 'stable'
          cache: true

      - name: Verify Flutter installation
        run: |
          flutter --version
          flutter doctor -v

      - name: Install Flutter dependencies
        run: flutter pub get

      - name: Select Xcode version
        run: sudo xcode-select -s /Applications/Xcode_${{ env.XCODE_VERSION }}.app/Contents/Developer

      - name: Verify Xcode setup
        run: |
          xcodebuild -version
          xcodebuild -showsdks

      - name: Install CocoaPods dependencies
        working-directory: ios
        run: |
          pod install --repo-update

      # Code Signing Setup (Required for Release builds)
      - name: Setup iOS code signing (Release only)
        if: github.event.inputs.build_type == 'release' || github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main'
        env:
          # These secrets need to be configured in GitHub repository settings:
          # - IOS_CERTIFICATE_BASE64: Base64 encoded .p12 certificate
          # - IOS_CERTIFICATE_PASSWORD: Password for .p12 certificate
          # - IOS_PROVISIONING_PROFILE_BASE64: Base64 encoded provisioning profile
          # - KEYCHAIN_PASSWORD: Temporary keychain password
          IOS_CERTIFICATE_BASE64: ${{ secrets.IOS_CERTIFICATE_BASE64 }}
          IOS_CERTIFICATE_PASSWORD: ${{ secrets.IOS_CERTIFICATE_PASSWORD }}
          IOS_PROVISIONING_PROFILE_BASE64: ${{ secrets.IOS_PROVISIONING_PROFILE_BASE64 }}
          KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
        run: |
          # Create variables
          CERTIFICATE_PATH=$RUNNER_TEMP/build_certificate.p12
          PP_PATH=$RUNNER_TEMP/build_pp.mobileprovision
          KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db

          # Import certificate and provisioning profile from secrets
          echo -n "$IOS_CERTIFICATE_BASE64" | base64 --decode -o $CERTIFICATE_PATH
          echo -n "$IOS_PROVISIONING_PROFILE_BASE64" | base64 --decode -o $PP_PATH

          # Create temporary keychain
          security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
          security set-keychain-settings -lut 21600 $KEYCHAIN_PATH
          security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH

          # Import certificate to keychain
          security import $CERTIFICATE_PATH -P "$IOS_CERTIFICATE_PASSWORD" -A -t cert -f pkcs12 -k $KEYCHAIN_PATH
          security list-keychain -d user -s $KEYCHAIN_PATH

          # Install provisioning profile
          mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles
          cp $PP_PATH ~/Library/MobileDevice/Provisioning\ Profiles

      - name: Build iOS app (Debug)
        if: github.event.inputs.build_type == 'debug' || (github.event.inputs.build_type == '' && github.event_name != 'push')
        run: |
          flutter build ios --debug --no-codesign

      - name: Build iOS app (Release)
        if: github.event.inputs.build_type == 'release' || github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main'
        run: |
          flutter build ios --release

      - name: Build IPA (Release with code signing)
        if: github.event.inputs.build_type == 'release' || github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main'
        working-directory: ios
        run: |
          xcodebuild -workspace Runner.xcworkspace \
            -scheme Runner \
            -configuration Release \
            -archivePath $RUNNER_TEMP/Runner.xcarchive \
            archive

          xcodebuild -exportArchive \
            -archivePath $RUNNER_TEMP/Runner.xcarchive \
            -exportPath $RUNNER_TEMP/build \
            -exportOptionsPlist Runner/ExportOptions.plist

      - name: Upload IPA artifact
        if: github.event.inputs.build_type == 'release' || github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main'
        uses: actions/upload-artifact@v4
        with:
          name: thai-idcard-reader-ios-${{ github.sha }}
          path: ${{ runner.temp }}/build/*.ipa
          retention-days: 30

      - name: Upload debug build artifact
        if: github.event.inputs.build_type == 'debug' || (github.event.inputs.build_type == '' && github.event_name != 'push')
        uses: actions/upload-artifact@v4
        with:
          name: thai-idcard-reader-ios-debug-${{ github.sha }}
          path: build/ios/iphoneos/Runner.app
          retention-days: 7

      - name: Cleanup keychain and provisioning profile
        if: always() && (github.event.inputs.build_type == 'release' || github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main')
        run: |
          security delete-keychain $RUNNER_TEMP/app-signing.keychain-db || true
          rm -rf ~/Library/MobileDevice/Provisioning\ Profiles/* || true

  analyze:
    runs-on: macos-14
    timeout-minutes: 20

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Flutter
        uses: subosito/flutter-action@v2
        with:
          flutter-version: ${{ env.FLUTTER_VERSION }}
          channel: 'stable'
          cache: true

      - name: Install dependencies
        run: flutter pub get

      - name: Analyze code
        run: flutter analyze

      - name: Check formatting
        run: dart format --set-exit-if-changed lib test

  test:
    runs-on: macos-14
    timeout-minutes: 20

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Flutter
        uses: subosito/flutter-action@v2
        with:
          flutter-version: ${{ env.FLUTTER_VERSION }}
          channel: 'stable'
          cache: true

      - name: Install dependencies
        run: flutter pub get

      - name: Run tests
        run: flutter test --coverage

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v4
        with:
          files: ./coverage/lcov.info
          flags: flutter
          name: flutter-coverage
