@blackcode_sa/metaestetics-api 1.13.21 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11860,10 +11860,21 @@ var practitionerInvitationTemplate = `
11860
11860
 
11861
11861
  <p>This token will expire on <strong>{{expirationDate}}</strong>.</p>
11862
11862
 
11863
- <p>To create your account:</p>
11863
+ <p><strong>You have two options to create your account:</strong></p>
11864
+
11865
+ <p><strong>Option 1: Sign in with Google (Recommended)</strong></p>
11866
+ <ol>
11867
+ <li>Open the MetaEsthetics Doctor App</li>
11868
+ <li>Click "Sign in with Google" on the login screen</li>
11869
+ <li>Select your Google account (use the email address: {{practitionerEmail}})</li>
11870
+ <li>You'll see an invitation to join {{clinicName}} - simply select it and join!</li>
11871
+ </ol>
11872
+
11873
+ <p><strong>Option 2: Use Email/Password with Token</strong></p>
11864
11874
  <ol>
11865
11875
  <li>Visit {{registrationUrl}}</li>
11866
- <li>Enter your email and create a password</li>
11876
+ <li>Click "Claim Existing Profile with Token"</li>
11877
+ <li>Enter your email ({{practitionerEmail}}) and create a password</li>
11867
11878
  <li>When prompted, enter the token above</li>
11868
11879
  </ol>
11869
11880
 
@@ -11787,10 +11787,21 @@ var practitionerInvitationTemplate = `
11787
11787
 
11788
11788
  <p>This token will expire on <strong>{{expirationDate}}</strong>.</p>
11789
11789
 
11790
- <p>To create your account:</p>
11790
+ <p><strong>You have two options to create your account:</strong></p>
11791
+
11792
+ <p><strong>Option 1: Sign in with Google (Recommended)</strong></p>
11793
+ <ol>
11794
+ <li>Open the MetaEsthetics Doctor App</li>
11795
+ <li>Click "Sign in with Google" on the login screen</li>
11796
+ <li>Select your Google account (use the email address: {{practitionerEmail}})</li>
11797
+ <li>You'll see an invitation to join {{clinicName}} - simply select it and join!</li>
11798
+ </ol>
11799
+
11800
+ <p><strong>Option 2: Use Email/Password with Token</strong></p>
11791
11801
  <ol>
11792
11802
  <li>Visit {{registrationUrl}}</li>
11793
- <li>Enter your email and create a password</li>
11803
+ <li>Click "Claim Existing Profile with Token"</li>
11804
+ <li>Enter your email ({{practitionerEmail}}) and create a password</li>
11794
11805
  <li>When prompted, enter the token above</li>
11795
11806
  </ol>
11796
11807
 
package/dist/index.d.mts CHANGED
@@ -7029,6 +7029,37 @@ declare class PractitionerService extends BaseService {
7029
7029
  * - Fields: basicInfo.email (Ascending), status (Ascending), userRef (Ascending)
7030
7030
  */
7031
7031
  findDraftPractitionerByEmail(email: string): Promise<Practitioner | null>;
7032
+ /**
7033
+ * Finds all draft practitioner profiles by email address
7034
+ * Used when a doctor signs in with Google to show all clinic invitations
7035
+ *
7036
+ * @param email - Email address to search for
7037
+ * @returns Array of draft practitioner profiles with clinic information
7038
+ *
7039
+ * @remarks
7040
+ * Requires Firestore composite index on:
7041
+ * - Collection: practitioners
7042
+ * - Fields: basicInfo.email (Ascending), status (Ascending), userRef (Ascending)
7043
+ */
7044
+ getDraftProfilesByEmail(email: string): Promise<Practitioner[]>;
7045
+ /**
7046
+ * Claims a draft practitioner profile and links it to a user account
7047
+ * Used when a doctor selects which clinic(s) to join after Google Sign-In
7048
+ *
7049
+ * @param practitionerId - ID of the draft practitioner profile to claim
7050
+ * @param userId - ID of the user account to link the profile to
7051
+ * @returns The claimed practitioner profile
7052
+ */
7053
+ claimDraftProfileWithGoogle(practitionerId: string, userId: string): Promise<Practitioner>;
7054
+ /**
7055
+ * Claims multiple draft practitioner profiles and merges them into one profile
7056
+ * Used when a doctor selects multiple clinics to join after Google Sign-In
7057
+ *
7058
+ * @param practitionerIds - Array of draft practitioner profile IDs to claim
7059
+ * @param userId - ID of the user account to link the profiles to
7060
+ * @returns The claimed practitioner profile (first one becomes main, others merged)
7061
+ */
7062
+ claimMultipleDraftProfilesWithGoogle(practitionerIds: string[], userId: string): Promise<Practitioner>;
7032
7063
  /**
7033
7064
  * Dohvata sve zdravstvene radnike za određenu kliniku sa statusom ACTIVE
7034
7065
  */
@@ -8404,6 +8435,18 @@ declare class AuthService extends BaseService {
8404
8435
  * @returns The signed-in or newly created user.
8405
8436
  */
8406
8437
  signInWithGoogleIdToken(idToken: string, initialRole?: UserRole): Promise<User>;
8438
+ /**
8439
+ * Signs up or signs in a practitioner with Google authentication.
8440
+ * Checks for existing practitioner account or draft profiles.
8441
+ *
8442
+ * @param idToken - The Google ID token obtained from the mobile app
8443
+ * @returns Object containing user, practitioner (if exists), and draft profiles (if any)
8444
+ */
8445
+ signUpPractitionerWithGoogle(idToken: string): Promise<{
8446
+ user: User;
8447
+ practitioner: Practitioner | null;
8448
+ draftProfiles: Practitioner[];
8449
+ }>;
8407
8450
  /**
8408
8451
  * Links a Google account to the currently signed-in user using an ID token.
8409
8452
  * This is used to upgrade an anonymous user or to allow an existing user
package/dist/index.d.ts CHANGED
@@ -7029,6 +7029,37 @@ declare class PractitionerService extends BaseService {
7029
7029
  * - Fields: basicInfo.email (Ascending), status (Ascending), userRef (Ascending)
7030
7030
  */
7031
7031
  findDraftPractitionerByEmail(email: string): Promise<Practitioner | null>;
7032
+ /**
7033
+ * Finds all draft practitioner profiles by email address
7034
+ * Used when a doctor signs in with Google to show all clinic invitations
7035
+ *
7036
+ * @param email - Email address to search for
7037
+ * @returns Array of draft practitioner profiles with clinic information
7038
+ *
7039
+ * @remarks
7040
+ * Requires Firestore composite index on:
7041
+ * - Collection: practitioners
7042
+ * - Fields: basicInfo.email (Ascending), status (Ascending), userRef (Ascending)
7043
+ */
7044
+ getDraftProfilesByEmail(email: string): Promise<Practitioner[]>;
7045
+ /**
7046
+ * Claims a draft practitioner profile and links it to a user account
7047
+ * Used when a doctor selects which clinic(s) to join after Google Sign-In
7048
+ *
7049
+ * @param practitionerId - ID of the draft practitioner profile to claim
7050
+ * @param userId - ID of the user account to link the profile to
7051
+ * @returns The claimed practitioner profile
7052
+ */
7053
+ claimDraftProfileWithGoogle(practitionerId: string, userId: string): Promise<Practitioner>;
7054
+ /**
7055
+ * Claims multiple draft practitioner profiles and merges them into one profile
7056
+ * Used when a doctor selects multiple clinics to join after Google Sign-In
7057
+ *
7058
+ * @param practitionerIds - Array of draft practitioner profile IDs to claim
7059
+ * @param userId - ID of the user account to link the profiles to
7060
+ * @returns The claimed practitioner profile (first one becomes main, others merged)
7061
+ */
7062
+ claimMultipleDraftProfilesWithGoogle(practitionerIds: string[], userId: string): Promise<Practitioner>;
7032
7063
  /**
7033
7064
  * Dohvata sve zdravstvene radnike za određenu kliniku sa statusom ACTIVE
7034
7065
  */
@@ -8404,6 +8435,18 @@ declare class AuthService extends BaseService {
8404
8435
  * @returns The signed-in or newly created user.
8405
8436
  */
8406
8437
  signInWithGoogleIdToken(idToken: string, initialRole?: UserRole): Promise<User>;
8438
+ /**
8439
+ * Signs up or signs in a practitioner with Google authentication.
8440
+ * Checks for existing practitioner account or draft profiles.
8441
+ *
8442
+ * @param idToken - The Google ID token obtained from the mobile app
8443
+ * @returns Object containing user, practitioner (if exists), and draft profiles (if any)
8444
+ */
8445
+ signUpPractitionerWithGoogle(idToken: string): Promise<{
8446
+ user: User;
8447
+ practitioner: Practitioner | null;
8448
+ draftProfiles: Practitioner[];
8449
+ }>;
8407
8450
  /**
8408
8451
  * Links a Google account to the currently signed-in user using an ID token.
8409
8452
  * This is used to upgrade an anonymous user or to allow an existing user
package/dist/index.js CHANGED
@@ -11715,6 +11715,240 @@ var PractitionerService = class extends BaseService {
11715
11715
  return null;
11716
11716
  }
11717
11717
  }
11718
+ /**
11719
+ * Finds all draft practitioner profiles by email address
11720
+ * Used when a doctor signs in with Google to show all clinic invitations
11721
+ *
11722
+ * @param email - Email address to search for
11723
+ * @returns Array of draft practitioner profiles with clinic information
11724
+ *
11725
+ * @remarks
11726
+ * Requires Firestore composite index on:
11727
+ * - Collection: practitioners
11728
+ * - Fields: basicInfo.email (Ascending), status (Ascending), userRef (Ascending)
11729
+ */
11730
+ async getDraftProfilesByEmail(email) {
11731
+ try {
11732
+ const normalizedEmail = email.toLowerCase().trim();
11733
+ console.log("[PRACTITIONER] Searching for all draft practitioners by email", {
11734
+ email: normalizedEmail
11735
+ });
11736
+ const q = (0, import_firestore32.query)(
11737
+ (0, import_firestore32.collection)(this.db, PRACTITIONERS_COLLECTION),
11738
+ (0, import_firestore32.where)("basicInfo.email", "==", normalizedEmail),
11739
+ (0, import_firestore32.where)("status", "==", "draft" /* DRAFT */),
11740
+ (0, import_firestore32.where)("userRef", "==", "")
11741
+ );
11742
+ const querySnapshot = await (0, import_firestore32.getDocs)(q);
11743
+ if (querySnapshot.empty) {
11744
+ console.log("[PRACTITIONER] No draft practitioners found for email", {
11745
+ email: normalizedEmail
11746
+ });
11747
+ return [];
11748
+ }
11749
+ const draftPractitioners = querySnapshot.docs.map(
11750
+ (doc47) => doc47.data()
11751
+ );
11752
+ console.log("[PRACTITIONER] Found draft practitioners", {
11753
+ email: normalizedEmail,
11754
+ count: draftPractitioners.length,
11755
+ practitionerIds: draftPractitioners.map((p) => p.id)
11756
+ });
11757
+ return draftPractitioners;
11758
+ } catch (error) {
11759
+ console.error(
11760
+ "[PRACTITIONER] Error finding draft practitioners by email:",
11761
+ error
11762
+ );
11763
+ return [];
11764
+ }
11765
+ }
11766
+ /**
11767
+ * Claims a draft practitioner profile and links it to a user account
11768
+ * Used when a doctor selects which clinic(s) to join after Google Sign-In
11769
+ *
11770
+ * @param practitionerId - ID of the draft practitioner profile to claim
11771
+ * @param userId - ID of the user account to link the profile to
11772
+ * @returns The claimed practitioner profile
11773
+ */
11774
+ async claimDraftProfileWithGoogle(practitionerId, userId) {
11775
+ try {
11776
+ console.log("[PRACTITIONER] Claiming draft profile with Google", {
11777
+ practitionerId,
11778
+ userId
11779
+ });
11780
+ const practitioner = await this.getPractitioner(practitionerId);
11781
+ if (!practitioner) {
11782
+ throw new Error(`Practitioner ${practitionerId} not found`);
11783
+ }
11784
+ if (practitioner.status !== "draft" /* DRAFT */) {
11785
+ throw new Error("This practitioner profile has already been claimed");
11786
+ }
11787
+ const existingPractitioner = await this.getPractitionerByUserRef(userId);
11788
+ if (existingPractitioner) {
11789
+ console.log("[PRACTITIONER] User already has profile, merging clinics");
11790
+ const mergedClinics = Array.from(/* @__PURE__ */ new Set([
11791
+ ...existingPractitioner.clinics,
11792
+ ...practitioner.clinics
11793
+ ]));
11794
+ const mergedWorkingHours = [...existingPractitioner.clinicWorkingHours];
11795
+ for (const workingHours of practitioner.clinicWorkingHours) {
11796
+ if (!mergedWorkingHours.find((wh) => wh.clinicId === workingHours.clinicId)) {
11797
+ mergedWorkingHours.push(workingHours);
11798
+ }
11799
+ }
11800
+ const mergedClinicsInfo = [...existingPractitioner.clinicsInfo];
11801
+ for (const clinicInfo of practitioner.clinicsInfo) {
11802
+ if (!mergedClinicsInfo.find((ci) => ci.id === clinicInfo.id)) {
11803
+ mergedClinicsInfo.push(clinicInfo);
11804
+ }
11805
+ }
11806
+ const updatedPractitioner2 = await this.updatePractitioner(existingPractitioner.id, {
11807
+ clinics: mergedClinics,
11808
+ clinicWorkingHours: mergedWorkingHours,
11809
+ clinicsInfo: mergedClinicsInfo
11810
+ });
11811
+ await (0, import_firestore32.deleteDoc)((0, import_firestore32.doc)(this.db, PRACTITIONERS_COLLECTION, practitionerId));
11812
+ const activeTokens2 = await this.getPractitionerActiveTokens(practitionerId);
11813
+ for (const token of activeTokens2) {
11814
+ await this.markTokenAsUsed(token.id, practitionerId, userId);
11815
+ }
11816
+ return updatedPractitioner2;
11817
+ }
11818
+ const updatedPractitioner = await this.updatePractitioner(practitioner.id, {
11819
+ userRef: userId,
11820
+ status: "active" /* ACTIVE */
11821
+ });
11822
+ const activeTokens = await this.getPractitionerActiveTokens(practitionerId);
11823
+ for (const token of activeTokens) {
11824
+ await this.markTokenAsUsed(token.id, practitionerId, userId);
11825
+ }
11826
+ console.log("[PRACTITIONER] Draft profile claimed successfully", {
11827
+ practitionerId: updatedPractitioner.id,
11828
+ userId
11829
+ });
11830
+ return updatedPractitioner;
11831
+ } catch (error) {
11832
+ console.error(
11833
+ "[PRACTITIONER] Error claiming draft profile with Google:",
11834
+ error
11835
+ );
11836
+ throw error;
11837
+ }
11838
+ }
11839
+ /**
11840
+ * Claims multiple draft practitioner profiles and merges them into one profile
11841
+ * Used when a doctor selects multiple clinics to join after Google Sign-In
11842
+ *
11843
+ * @param practitionerIds - Array of draft practitioner profile IDs to claim
11844
+ * @param userId - ID of the user account to link the profiles to
11845
+ * @returns The claimed practitioner profile (first one becomes main, others merged)
11846
+ */
11847
+ async claimMultipleDraftProfilesWithGoogle(practitionerIds, userId) {
11848
+ try {
11849
+ if (practitionerIds.length === 0) {
11850
+ throw new Error("No practitioner IDs provided");
11851
+ }
11852
+ console.log("[PRACTITIONER] Claiming multiple draft profiles with Google", {
11853
+ practitionerIds,
11854
+ userId,
11855
+ count: practitionerIds.length
11856
+ });
11857
+ const draftProfiles = await Promise.all(
11858
+ practitionerIds.map((id) => this.getPractitioner(id))
11859
+ );
11860
+ const validDrafts = draftProfiles.filter((p) => {
11861
+ if (!p) return false;
11862
+ if (p.status !== "draft" /* DRAFT */) {
11863
+ throw new Error(`Practitioner ${p.id} has already been claimed`);
11864
+ }
11865
+ return true;
11866
+ });
11867
+ if (validDrafts.length === 0) {
11868
+ throw new Error("No valid draft profiles found");
11869
+ }
11870
+ const existingPractitioner = await this.getPractitionerByUserRef(userId);
11871
+ if (existingPractitioner) {
11872
+ let mergedClinics2 = new Set(existingPractitioner.clinics);
11873
+ let mergedWorkingHours2 = [...existingPractitioner.clinicWorkingHours];
11874
+ let mergedClinicsInfo2 = [...existingPractitioner.clinicsInfo];
11875
+ for (const draft of validDrafts) {
11876
+ draft.clinics.forEach((clinicId) => mergedClinics2.add(clinicId));
11877
+ for (const workingHours of draft.clinicWorkingHours) {
11878
+ if (!mergedWorkingHours2.find((wh) => wh.clinicId === workingHours.clinicId)) {
11879
+ mergedWorkingHours2.push(workingHours);
11880
+ }
11881
+ }
11882
+ for (const clinicInfo of draft.clinicsInfo) {
11883
+ if (!mergedClinicsInfo2.find((ci) => ci.id === clinicInfo.id)) {
11884
+ mergedClinicsInfo2.push(clinicInfo);
11885
+ }
11886
+ }
11887
+ }
11888
+ const updatedPractitioner2 = await this.updatePractitioner(existingPractitioner.id, {
11889
+ clinics: Array.from(mergedClinics2),
11890
+ clinicWorkingHours: mergedWorkingHours2,
11891
+ clinicsInfo: mergedClinicsInfo2
11892
+ });
11893
+ for (const draft of validDrafts) {
11894
+ await (0, import_firestore32.deleteDoc)((0, import_firestore32.doc)(this.db, PRACTITIONERS_COLLECTION, draft.id));
11895
+ const activeTokens = await this.getPractitionerActiveTokens(draft.id);
11896
+ for (const token of activeTokens) {
11897
+ await this.markTokenAsUsed(token.id, draft.id, userId);
11898
+ }
11899
+ }
11900
+ return updatedPractitioner2;
11901
+ }
11902
+ const mainDraft = validDrafts[0];
11903
+ const otherDrafts = validDrafts.slice(1);
11904
+ let mergedClinics = new Set(mainDraft.clinics);
11905
+ let mergedWorkingHours = [...mainDraft.clinicWorkingHours];
11906
+ let mergedClinicsInfo = [...mainDraft.clinicsInfo];
11907
+ for (const draft of otherDrafts) {
11908
+ draft.clinics.forEach((clinicId) => mergedClinics.add(clinicId));
11909
+ for (const workingHours of draft.clinicWorkingHours) {
11910
+ if (!mergedWorkingHours.find((wh) => wh.clinicId === workingHours.clinicId)) {
11911
+ mergedWorkingHours.push(workingHours);
11912
+ }
11913
+ }
11914
+ for (const clinicInfo of draft.clinicsInfo) {
11915
+ if (!mergedClinicsInfo.find((ci) => ci.id === clinicInfo.id)) {
11916
+ mergedClinicsInfo.push(clinicInfo);
11917
+ }
11918
+ }
11919
+ }
11920
+ const updatedPractitioner = await this.updatePractitioner(mainDraft.id, {
11921
+ userRef: userId,
11922
+ status: "active" /* ACTIVE */,
11923
+ clinics: Array.from(mergedClinics),
11924
+ clinicWorkingHours: mergedWorkingHours,
11925
+ clinicsInfo: mergedClinicsInfo
11926
+ });
11927
+ const mainActiveTokens = await this.getPractitionerActiveTokens(mainDraft.id);
11928
+ for (const token of mainActiveTokens) {
11929
+ await this.markTokenAsUsed(token.id, mainDraft.id, userId);
11930
+ }
11931
+ for (const draft of otherDrafts) {
11932
+ await (0, import_firestore32.deleteDoc)((0, import_firestore32.doc)(this.db, PRACTITIONERS_COLLECTION, draft.id));
11933
+ const activeTokens = await this.getPractitionerActiveTokens(draft.id);
11934
+ for (const token of activeTokens) {
11935
+ await this.markTokenAsUsed(token.id, draft.id, userId);
11936
+ }
11937
+ }
11938
+ console.log("[PRACTITIONER] Multiple draft profiles claimed successfully", {
11939
+ practitionerId: updatedPractitioner.id,
11940
+ userId,
11941
+ mergedCount: validDrafts.length
11942
+ });
11943
+ return updatedPractitioner;
11944
+ } catch (error) {
11945
+ console.error(
11946
+ "[PRACTITIONER] Error claiming multiple draft profiles with Google:",
11947
+ error
11948
+ );
11949
+ throw error;
11950
+ }
11951
+ }
11718
11952
  /**
11719
11953
  * Dohvata sve zdravstvene radnike za određenu kliniku sa statusom ACTIVE
11720
11954
  */
@@ -15787,6 +16021,135 @@ var AuthService = class extends BaseService {
15787
16021
  throw handleFirebaseError(error);
15788
16022
  }
15789
16023
  }
16024
+ /**
16025
+ * Signs up or signs in a practitioner with Google authentication.
16026
+ * Checks for existing practitioner account or draft profiles.
16027
+ *
16028
+ * @param idToken - The Google ID token obtained from the mobile app
16029
+ * @returns Object containing user, practitioner (if exists), and draft profiles (if any)
16030
+ */
16031
+ async signUpPractitionerWithGoogle(idToken) {
16032
+ try {
16033
+ console.log("[AUTH] Starting practitioner Google Sign-In/Sign-Up");
16034
+ let email;
16035
+ try {
16036
+ const payloadBase64 = idToken.split(".")[1];
16037
+ const payloadJson = globalThis.atob ? globalThis.atob(payloadBase64) : Buffer.from(payloadBase64, "base64").toString("utf8");
16038
+ const payload = JSON.parse(payloadJson);
16039
+ email = payload.email;
16040
+ } catch (decodeError) {
16041
+ console.error("[AUTH] Failed to decode email from Google ID token:", decodeError);
16042
+ throw new AuthError(
16043
+ "Unable to read email from Google token. Please try again.",
16044
+ "AUTH/INVALID_GOOGLE_TOKEN",
16045
+ 400
16046
+ );
16047
+ }
16048
+ if (!email) {
16049
+ throw new AuthError(
16050
+ "Unable to read email from Google token. Please try again.",
16051
+ "AUTH/INVALID_GOOGLE_TOKEN",
16052
+ 400
16053
+ );
16054
+ }
16055
+ const normalizedEmail = email.toLowerCase().trim();
16056
+ console.log("[AUTH] Extracted email from Google token:", normalizedEmail);
16057
+ const methods = await (0, import_auth8.fetchSignInMethodsForEmail)(this.auth, normalizedEmail);
16058
+ const hasGoogleMethod = methods.includes(import_auth8.GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD);
16059
+ const hasEmailMethod = methods.includes(import_auth8.EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD);
16060
+ const practitionerService = new PractitionerService(this.db, this.auth, this.app);
16061
+ if (hasGoogleMethod) {
16062
+ console.log("[AUTH] User exists with Google provider, signing in");
16063
+ const credential2 = import_auth8.GoogleAuthProvider.credential(idToken);
16064
+ const { user: firebaseUser2 } = await (0, import_auth8.signInWithCredential)(this.auth, credential2);
16065
+ const existingUser2 = await this.userService.getUserById(firebaseUser2.uid);
16066
+ if (!existingUser2) {
16067
+ await (0, import_auth8.signOut)(this.auth);
16068
+ throw new AuthError(
16069
+ "No account found. Please contact support.",
16070
+ "AUTH/USER_NOT_FOUND",
16071
+ 404
16072
+ );
16073
+ }
16074
+ let practitioner2 = null;
16075
+ if (existingUser2.practitionerProfile) {
16076
+ practitioner2 = await practitionerService.getPractitioner(existingUser2.practitionerProfile);
16077
+ }
16078
+ const draftProfiles2 = await practitionerService.getDraftProfilesByEmail(normalizedEmail);
16079
+ return {
16080
+ user: existingUser2,
16081
+ practitioner: practitioner2,
16082
+ draftProfiles: draftProfiles2
16083
+ };
16084
+ }
16085
+ if (hasEmailMethod && !hasGoogleMethod) {
16086
+ console.log("[AUTH] User exists with email/password only");
16087
+ throw new AuthError(
16088
+ "An account with this email already exists. Please sign in with your email and password, then link your Google account in settings.",
16089
+ "AUTH/EMAIL_ALREADY_EXISTS",
16090
+ 409
16091
+ );
16092
+ }
16093
+ console.log("[AUTH] Signing in with Google credential");
16094
+ const credential = import_auth8.GoogleAuthProvider.credential(idToken);
16095
+ let firebaseUser;
16096
+ try {
16097
+ const result = await (0, import_auth8.signInWithCredential)(this.auth, credential);
16098
+ firebaseUser = result.user;
16099
+ } catch (error) {
16100
+ if (error.code === "auth/account-exists-with-different-credential") {
16101
+ throw new AuthError(
16102
+ "An account with this email already exists. Please sign in with your email and password, then link your Google account in settings.",
16103
+ "AUTH/EMAIL_ALREADY_EXISTS",
16104
+ 409
16105
+ );
16106
+ }
16107
+ throw error;
16108
+ }
16109
+ let existingUser = null;
16110
+ try {
16111
+ const existingUserDoc = await this.userService.getUserById(firebaseUser.uid);
16112
+ if (existingUserDoc) {
16113
+ existingUser = existingUserDoc;
16114
+ console.log("[AUTH] Found existing User document");
16115
+ }
16116
+ } catch (error) {
16117
+ console.error("[AUTH] Error checking for existing user:", error);
16118
+ }
16119
+ console.log("[AUTH] Checking for draft profiles");
16120
+ const draftProfiles = await practitionerService.getDraftProfilesByEmail(normalizedEmail);
16121
+ let user;
16122
+ if (existingUser) {
16123
+ user = existingUser;
16124
+ console.log("[AUTH] Using existing user account");
16125
+ } else {
16126
+ user = await this.userService.createUser(firebaseUser, ["practitioner" /* PRACTITIONER */], {
16127
+ skipProfileCreation: true
16128
+ });
16129
+ console.log("[AUTH] Created new user account");
16130
+ }
16131
+ let practitioner = null;
16132
+ if (user.practitionerProfile) {
16133
+ practitioner = await practitionerService.getPractitioner(user.practitionerProfile);
16134
+ }
16135
+ console.log("[AUTH] Google Sign-In complete", {
16136
+ userId: user.uid,
16137
+ hasPractitioner: !!practitioner,
16138
+ draftProfilesCount: draftProfiles.length
16139
+ });
16140
+ return {
16141
+ user,
16142
+ practitioner,
16143
+ draftProfiles
16144
+ };
16145
+ } catch (error) {
16146
+ console.error("[AUTH] Error in signUpPractitionerWithGoogle:", error);
16147
+ if (error instanceof AuthError) {
16148
+ throw error;
16149
+ }
16150
+ throw handleFirebaseError(error);
16151
+ }
16152
+ }
15790
16153
  /**
15791
16154
  * Links a Google account to the currently signed-in user using an ID token.
15792
16155
  * This is used to upgrade an anonymous user or to allow an existing user