name: Publish to pub.dev

on:
  release:
    types: [published]

jobs:
  publish:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v4

      - name: Validate release tag (no v prefix)
        run: |
          TAG="${{ gitea.event.release.tag_name }}"
          if [[ "$TAG" == v* ]]; then
            echo "Error: tag '$TAG' has a v prefix. Use '0.1.0' not 'v0.1.0'"
            exit 1
          fi
          echo "Publishing version: $TAG"

      - name: Verify version matches pubspec
        run: |
          TAG="${{ gitea.event.release.tag_name }}"
          PUBSPEC_VERSION=$(grep '^version:' pubspec.yaml | awk '{print $2}')
          if [ "$TAG" != "$PUBSPEC_VERSION" ]; then
            echo "Error: tag '$TAG' doesn't match pubspec version '$PUBSPEC_VERSION'"
            exit 1
          fi

      - name: Install Flutter
        uses: subosito/flutter-action@v2
        with:
          channel: stable

      - name: Install Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.23'

      - name: Build xcframework from Go source
        run: |
          chmod +x build_go.sh
          ./build_go.sh

      - name: Verify xcframework exists
        run: |
          ls -lh ios/TailscaleKit.xcframework/ios-arm64/TailscaleKit.framework/TailscaleKit
          ls -lh ios/TailscaleKit.xcframework/ios-arm64-simulator/TailscaleKit.framework/TailscaleKit

      - name: Write pub.dev credentials
        run: |
          mkdir -p "$HOME/Library/Application Support/dart"
          cat > "$HOME/Library/Application Support/dart/pub-credentials.json" <<EOF
          {
            "accessToken": "initial",
            "refreshToken": "${{ secrets.PUB_DEV_REFRESH_TOKEN }}",
            "tokenEndpoint": "https://accounts.google.com/o/oauth2/token",
            "scopes": ["openid", "https://www.googleapis.com/auth/userinfo.email"],
            "expiration": 0
          }
          EOF

      - name: Dry run publish
        run: dart pub publish --dry-run

      - name: Publish to pub.dev
        run: dart pub publish --force
