File size: 11,833 Bytes
d96d2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3ec6da
 
 
 
 
 
 
 
 
 
4bb3f21
7d2f8a2
d3ec6da
 
 
d96d2a2
 
 
d3ec6da
 
 
d96d2a2
 
 
d3ec6da
 
 
 
 
 
 
 
d96d2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3ec6da
 
 
66a783c
d3ec6da
 
 
 
 
d96d2a2
 
d3ec6da
 
 
 
 
 
 
 
d96d2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3ec6da
 
 
 
d96d2a2
 
d3ec6da
d96d2a2
 
 
 
 
 
d3ec6da
 
 
d96d2a2
 
 
 
 
 
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { supabase } from '../lib/supabaseClient';
import useTicketStore from './ticketStore';

const useAuthStore = create(
    persist(
        (set, get) => ({
            // --- AUTH STATE ---
            user: null,
            profile: null,
            loading: false,

            // --- SUPABASE AUTH METHODS ---

            // Helper to fetch profile linked to auth user
            getProfile: async (user) => {
                if (!user) return null;

                const metadata = user.user_metadata || {};
                const currentProfile = get().profile;

                // 1. Resolve FROM METADATA or PERSISTED state
                // Priority 1: If we have a persisted session for THIS user and it's active, keep it 
                // to prevent temporary lobbies during refresh/tab switching.
                if (currentProfile && currentProfile.id === user.id && currentProfile.status === 'active') {
                    console.log("Active profile retained from state.");
                    // Background fetch to ensure session is still valid/synced
                    get()._syncProfile(user.id);
                    return currentProfile;
                }

                // Priority 2: Use Auth Metadata (Instant fallback)
                const isMasterAdmin = user.email === 'masteradmin@helpdesk.ai';

                const instantProfile = {
                    id: user.id,
                    email: user.email,
                    full_name: isMasterAdmin ? 'Master Admin' : (metadata.full_name || 'User'),
                    role: isMasterAdmin ? 'master_admin' : (metadata.role || 'user'),
                    status: isMasterAdmin ? 'active' : 'pending_email_verification',
                    company: metadata.company || ''
                };

                // 2. Sync with Database First before setting a fallback
                // This prevents flashes of 'pending_email_verification' when returning from magic links
                const dbProfile = await get()._syncProfile(user.id);
                if (dbProfile) {
                    return dbProfile;
                }

                console.log("Falling back to instant profile resolved from metadata:", instantProfile.role);
                set({ profile: instantProfile });
                return instantProfile;
            },

            // Helper for DB-side profile syncing
            _syncProfile: async (userId) => {
                try {
                    const { data, error } = await supabase
                        .from('profiles')
                        .select('*')
                        .eq('id', userId)
                        .single();

                    if (data) {
                        console.log("Database profile found, upgrading state.");
                        set({ profile: data });
                        return data;
                    }

                    if (error && error.code !== 'PGRST116') {
                        console.warn("DB Profile fetch error:", error.message);
                    }
                } catch (e) {
                    console.error("Background profile fetch error:", e);
                }
                return null;
            },

            getCurrentUser: async () => {
                try {
                    const { data: { user }, error } = await supabase.auth.getUser();
                    if (error) throw error;

                    if (user) {
                        set({ user });
                        // Don't 'await' here because we want 'loading: false' ASAP
                        get().getProfile(user);
                    } else {
                        set({ user: null, profile: null });
                    }
                    return user;
                    // eslint-disable-next-line no-unused-vars
                } catch (error) {
                    set({ user: null, profile: null });
                    return null;
                } finally {
                    set({ loading: false });
                }
            },

            login: async (email, password) => {
                set({ loading: true });
                console.log("Attempting login for:", email);
                try {
                    const { data, error } = await supabase.auth.signInWithPassword({
                        email,
                        password,
                    });

                    if (error) throw error;

                    const user = data.user;
                    set({ user });

                    console.log("Login successful, resolving profile...");
                    // This will resolve instantly from metadata AND try to update from DB
                    const profile = await get().getProfile(user);

                    // Block login entirely if email is unverified (for both users and admins)
                    if (profile?.status === 'pending_email_verification') {
                        await supabase.auth.signOut();
                        set({ user: null, profile: null });
                        throw new Error("Please verify your email address before continuing. Check your inbox.");
                    }

                    return { user, profile };
                } catch (error) {
                    console.error("Login operation failed:", error.message);
                    throw error;
                } finally {
                    set({ loading: false });
                }
            },

            signInWithMagicLink: async (email) => {
                set({ loading: true });
                console.log("Attempting magic link / OTP login for:", email);
                try {
                    const { error } = await supabase.auth.signInWithOtp({
                        email,
                        options: {
                            shouldCreateUser: false, // Only existing users
                        }
                    });

                    if (error) throw error;
                    return true;
                } catch (error) {
                    console.error("Magic link operation failed:", error.message);
                    throw error;
                } finally {
                    set({ loading: false });
                }
            },

            verifyOtpAndLogin: async (email, token, type = 'magiclink') => {
                set({ loading: true });
                console.log("Attempting OTP verification for:", email);
                try {
                    const { data, error } = await supabase.auth.verifyOtp({
                        email,
                        token,
                        type,
                    });

                    if (error) throw error;

                    const user = data.user;
                    set({ user });

                    console.log("OTP Login successful, resolving profile...");
                    const profile = await get().getProfile(user);

                    if (profile?.status === 'pending_email_verification') {
                        await supabase.auth.signOut();
                        set({ user: null, profile: null });
                        throw new Error("Please verify your email address before continuing.");
                    }
                    return { user, profile };
                } catch (error) {
                    console.error("OTP verification failed:", error.message);
                    throw error;
                } finally {
                    set({ loading: false });
                }
            },

            signup: async (email, password, fullName, role = 'user', company = '', extraMetadata = {}, emailRedirectTo = undefined) => {
                set({ loading: true });
                console.log("Starting signup for:", email);

                try {
                    // 1. Auth Signup with Metadata
                    console.log("Step 1: Auth.signUp...");
                    const { data, error } = await supabase.auth.signUp({
                        email,
                        password,
                        options: {
                            data: {
                                full_name: fullName,
                                role: role,
                                company: company,
                                ...extraMetadata
                            },
                            ...(emailRedirectTo && { emailRedirectTo })
                        }
                    });

                    if (error) {
                        console.error("Auth.signUp error:", error.message);
                        throw error;
                    }

                    if (data.user) {
                        console.log("Step 2: User created, resolving profile...");
                        set({ user: data.user });
                        await get().getProfile(data.user);
                    }

                    console.log("Signup complete!");
                    return data.user;
                } catch (error) {
                    console.error("Signup operation failed:", error.message);
                    throw error;
                } finally {
                    set({ loading: false });
                }
            },

            logout: async () => {
                set({ loading: true });
                try {
                    const { error } = await supabase.auth.signOut();
                    if (error) throw error;
                    set({ user: null, profile: null });
                    // clear persisted ticket state to prevent cross-user data leakage
                    useTicketStore.getState().clearTicket();
                    useTicketStore.setState({ notifications: [], tickets: [] });
                } finally {
                    set({ loading: false });
                }
            },


            updateProfile: async (updates) => {
                const { profile } = get();
                if (!profile?.id) return;

                set({ loading: true });
                try {
                    const { data, error } = await supabase
                        .from('profiles')
                        .update(updates)
                        .eq('id', profile.id)
                        .select()
                        .single();

                    if (error) throw error;
                    if (data) {
                        set({ profile: data });
                        return data;
                    }
                } catch (err) {
                    console.error("Profile update failed:", err);
                    throw err;
                } finally {
                    set({ loading: false });
                }
            },

            _initialized: false,
            initialize: () => {
                if (get()._initialized) return;
                set({ _initialized: true });

                get().getCurrentUser();

                supabase.auth.onAuthStateChange(async (event, session) => {
                    console.log("Auth state change:", event);
                    if (session?.user) {
                        set({ user: session.user });
                        get().getProfile(session.user);
                    } else {
                        set({ user: null, profile: null });
                    }
                    set({ loading: false });
                });
            }
        }),
        {
            name: 'auth-storage',
            partialize: (state) => ({
                // We keep profile persisted for quick UI transitions, 
                // but session is handled by Supabase cookie/localStorage
                profile: state.profile
            }),
        }
    )
);

export default useAuthStore;