File size: 5,596 Bytes
71638d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  ReactNode,
} from "react";
import { Session, User } from "@supabase/supabase-js";
import { CONFIG_ERROR, supabase } from "../config/supabase";
import { config } from "../config/env";
import {
  GoogleSignin,
  statusCodes,
  isErrorWithCode,
} from "../lib/googleAuthSafe";
import { Alert } from "react-native";

interface AuthContextType {
  user: User | null;
  session: Session | null;
  loading: boolean;
  isDevMode: boolean;
  configError: string | null;
  signInWithGoogle: () => Promise<void>;
  continueWithDevMode: () => void;
  signOut: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

interface AuthProviderProps {
  children: ReactNode;
}

export function AuthProvider({ children }: AuthProviderProps) {
  const [user, setUser] = useState<User | null>(null);
  const [session, setSession] = useState<Session | null>(null);
  const [loading, setLoading] = useState(true);
  const [isDevMode, setIsDevMode] = useState(false);
  const [configError] = useState<string | null>(CONFIG_ERROR);

  useEffect(() => {
    if (!supabase) {
      setLoading(false);
      return;
    }

    try {
      GoogleSignin.configure({
        webClientId: config.GOOGLE_CLIENT_ID,
        scopes: ["email", "profile"],
        offlineAccess: true,
      });
    } catch (e: any) {
      if (e.message?.includes("RNGoogleSignin")) {
        console.warn(
          "Google Sign-In not supported in Expo Go. Use a development build or 'Dev Mode'.",
        );
      } else {
        console.error("Google Sign-In config error:", e);
      }
    }

    supabase.auth.getSession().then(({ data: { session } }) => {
      setSession(session);
      setUser(session?.user ?? null);
      setLoading(false);
    });

    const {
      data: { subscription },
    } = supabase.auth.onAuthStateChange((_event, session) => {
      setSession(session);
      setUser(session?.user ?? null);
      setLoading(false);
    });

    return () => {
      subscription.unsubscribe();
    };
  }, []);

  const signInWithGoogle = async () => {
    try {
      if (!supabase) {
        Alert.alert("Configuration Error", "Supabase is not configured.");
        return;
      }

      setLoading(true);

      // 1. Check Play Services (Android)
      try {
        await GoogleSignin.hasPlayServices();
      } catch (e: any) {
        if (e.message?.includes("RNGoogleSignin")) {
          Alert.alert(
            "Expo Go Detected",
            "Native Google Sign-In is not supported in Expo Go. Please use 'Dev Mode' or build a development client.",
          );
          setLoading(false);
          return;
        }
        throw e;
      }

      // 2. Native Sign In
      const userInfo = await GoogleSignin.signIn();

      // 3. Get ID Token
      if (userInfo.data?.idToken) {
        const { data, error } = await supabase.auth.signInWithIdToken({
          provider: "google",
          token: userInfo.data.idToken,
        });

        if (error) throw error;

        // Critical: Update state immediately to trigger UI refresh
        if (data.session) {
          setSession(data.session);
          setUser(data.session.user);
        }
      } else {
        throw new Error("No ID token returned from Google Sign-In");
      }
    } catch (error: any) {
      if (isErrorWithCode(error)) {
        switch (error.code) {
          case statusCodes.SIGN_IN_CANCELLED:
            console.log("User cancelled the login flow");
            break;
          case statusCodes.IN_PROGRESS:
            console.log("Sign in is in progress");
            break;
          case statusCodes.PLAY_SERVICES_NOT_AVAILABLE:
            Alert.alert(
              "Error",
              "Google Play Services not available or outdated.",
            );
            break;
          default:
            console.error("Google Sign-In Error:", error);
            Alert.alert("Google Sign-In Error", error.message);
        }
      } else {
        console.error("An error occurred:", error);
        Alert.alert("Sign-In Failed", error.message || "Unknown error");
      }
    } finally {
      setLoading(false);
    }
  };

  const continueWithDevMode = () => {
    const devUser: User = {
      id: "dev-user-123",
      email: "dev@citytracker.local",
      app_metadata: {},
      user_metadata: { full_name: "Dev User" },
      aud: "authenticated",
      created_at: new Date().toISOString(),
    };
    setUser(devUser);
    setIsDevMode(true);
    setLoading(false);
  };

  const signOut = async () => {
    try {
      setLoading(true);

      // Sign out from Google Native SDK first
      try {
        await GoogleSignin.signOut();
      } catch (e) {
        console.warn("Google Sign-Out error (ignoring):", e);
      }

      if (!isDevMode && supabase) {
        await supabase.auth.signOut();
      }
      setUser(null);
      setSession(null);
      setIsDevMode(false);
    } catch (error) {
      console.error("Sign out error:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        session,
        loading,
        isDevMode,
        configError,
        signInWithGoogle,
        continueWithDevMode,
        signOut,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
}