parameters:
- name: env
  displayName: environment
  type: string
  default: develop
  values:
  - production
  - staging
  - develop

steps:
- template: install-flutter.yml

- script: |
    sudo xcode-select -s /Applications/Xcode_26.2.app
    /usr/bin/xcodebuild -version
  displayName: "Select Xcode version"

- task: InstallAppleCertificate@2
  displayName: Install Apple Certificate
  inputs:
    certSecureFile: 'comwell_distribution.p12'
    certPwd: $(cert_pw)
    keychain: 'temp'

# Install Apple provisioning profile
- task: InstallAppleProvisioningProfile@1
  displayName: Install provisioning profile
  inputs:
    provProfileSecureFile: $(iosProvisionProfileFileName)

- task: UseNode@1
  inputs:
    version: 18.x
  displayName: 'Install Node.js'

- script: |
    npm install -g firebase-tools
    dart pub global activate flutterfire_cli
  displayName: "Install fluttefire"

- script: |
      flutter config --enable-swift-package-manager
  displayName: "Enable Swift Package Manager"

- script: |
    cd comwell_key_app
    git=$(sh /etc/profile; which git)
    bundleVersion=$("$git" log --pretty=oneline HEAD^@ |wc -l)
    offsetBuildNumber=$((bundleVersion+4520))
    /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $offsetBuildNumber" "ios/Runner/Info.plist" 
    echo "Updated build number in ios/Runner/Info.plist to $offsetBuildNumber"
  displayName: "Update build number"

- script: |
      cd comwell_key_app
      flutter build ipa --flavor $(flavor) --release --no-codesign
  displayName: "Build IPA"

- script: |
      cd comwell_key_app
      xcodebuild -workspace ios/Runner.xcworkspace -scheme $(iosScheme) -archivePath build/ios/archive/Runner.xcarchive archive
  displayName: "Archive"

- script: |
      cd comwell_key_app
      xcodebuild -exportArchive \
            -archivePath build/ios/archive/Runner.xcarchive \
            -exportOptionsPlist ios/$(iosExportOptionsPlist) \
            -exportPath output
  displayName: "Export"

- task: AppStoreRelease@1
  displayName: "Publish"
  inputs:
    releaseTrack: 'TestFlight'
    appIdentifier: $(iosBundleId)
    serviceEndpoint: "Apple"
    appType: 'iOS'
    ipaPath: 'comwell_key_app/output/*.ipa'
    shouldSkipWaitingForProcessing: true
    shouldSkipSubmission: true