createFirebaseProject function

Future<void> createFirebaseProject({
  1. required String clientId,
  2. required String packageName,
  3. required String firebaseProjectId,
})

Creates a new Firebase project or uses an existing one.

This function guides the user through the process of setting up a Firebase project for a given client. It checks for a logged-in Firebase user, lists existing projects, and prompts the user to either use an existing project or create a new one if a project with the specified firebaseProjectId already exists.

clientId The ID of the client for which the Firebase project is being created. packageName The package name of the application. firebaseProjectId The desired Firebase project ID.

Throws an Exception if no user is logged in to Firebase CLI, if retrieving project lists fails, or if the user provides an empty new project ID.

Implementation

Future<void> createFirebaseProject({
  required String clientId,
  required String packageName,
  required String firebaseProjectId,
}) async {
  try {
    // Step 1: Get the logged-in user
    logger.i('πŸ” Checking logged-in Firebase user...');
    final userResult = await Process.run('firebase', ['login:list', '--json']);
    if (userResult.exitCode != 0) {
      throw Exception('❌ Failed to retrieve Firebase user info.');
    }

    final userData = jsonDecode(userResult.stdout) as Map<String, dynamic>;
    if (userData['status'] != 'success' ||
        (userData['result'] as List).isEmpty) {
      throw Exception('❌ No user is logged in to Firebase CLI.');
    }

    final loggedInUser = userData['result'][0]['user'] as Map<String, dynamic>;
    final userEmail = loggedInUser['email'];
    logger.i('πŸ‘€ Logged in as: $userEmail');

    // Step 2: Get the list of Firebase projects
    logger.i('πŸ” Fetching the list of Firebase projects...');
    final projectsResult = await Process.run('firebase', [
      'projects:list',
      '--json',
    ]);
    if (projectsResult.exitCode != 0) {
      throw Exception('❌ Failed to retrieve the list of Firebase projects.');
    }

    final projectsJson =
        jsonDecode(projectsResult.stdout) as Map<String, dynamic>;
    final projectsData = projectsJson['results'] as List<dynamic>?;

    if (projectsData == null || projectsData.isEmpty) {
      logger.i('πŸ“‹ No existing Firebase projects found.');
    } else {
      logger.i('πŸ“‹ Current Firebase projects:');
      for (final project in projectsData) {
        logger.i(
          '   - ${project['projectId']} (${project['displayName']}) by ${project['projectOwner'] ?? 'Unknown'}',
        );
      }
    }

    // Step 3: Check if a project with the same ID exists
    final existingProject = projectsData?.firstWhere(
      (project) => project['projectId'] == firebaseProjectId,
      orElse: () => null,
    );

    if (existingProject != null) {
      // Prompt user to decide whether to use the existing project
      logger.i(
        '⚠️ A project with the ID "$firebaseProjectId" already exists (Display Name: ${existingProject['displayName']}).',
      );
      final choice = prompt('Do you want to use this existing project? (y/n):');

      if (choice.toLowerCase() == 'y') {
        logger.i('βœ… Using existing project: $firebaseProjectId');
        return;
      } else {
        logger.i(
          'πŸ”„ You chose not to use the existing project. Please provide a new project ID.',
        );
        final newProjectId = prompt(
          'Enter a new Firebase Project ID (e.g., my-new-project):',
        );
        if (newProjectId.isEmpty) {
          throw Exception('❌ Project ID cannot be empty.');
        }
        firebaseProjectId = newProjectId;
      }
    }

    // Step 4: Create a new Firebase project
    final displayName = '${toTitleCase(clientId)}-HR-Flutter';
    logger.i('πŸš€ Creating Firebase project: $firebaseProjectId...');
    await runCommand(
      'firebase',
      ['projects:create', '--display-name', displayName, firebaseProjectId],
      successMessage:
          'βœ… Firebase project created successfully: $firebaseProjectId',
    );
  } catch (e) {
    logger.e('❌ Error during Firebase project creation: $e');
  }
}