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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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
import { createClient } from "@/lib/supabase/client";

const API_URL = process.env.NEXT_PUBLIC_BACKEND_URL;

export type Thread = {
    thread_id: string;
    account_id: string | null;
    project_id?: string | null;
    is_public?: boolean;
    created_at: string;
    updated_at: string;
    metadata?: {
      workflow_id?: string;
      workflow_name?: string;
      workflow_run_name?: string;
      is_workflow_execution?: boolean;
      agent_id?: string;
      is_agent_builder?: boolean;
      [key: string]: any;
    };
    [key: string]: any;
  };
  
  export type Project = {
    id: string;
    name: string;
    description: string;
    account_id: string;
    created_at: string;
    updated_at?: string;
    sandbox: {
      vnc_preview?: string;
      sandbox_url?: string;
      id?: string;
      pass?: string;
    };
    is_public?: boolean;
    [key: string]: any;
  };
  

  export const getThread = async (threadId: string): Promise<Thread> => {
    const supabase = createClient();
    const { data, error } = await supabase
      .from('threads')
      .select('*')
      .eq('thread_id', threadId)
      .single();
  
    if (error) throw error;
  
    return data;
  };

export const updateThread = async (
    threadId: string,
    data: Partial<Thread>,
  ): Promise<Thread> => {
    const supabase = createClient();
  
    const updateData = { ...data };
  
    // Update the thread
    const { data: updatedThread, error } = await supabase
      .from('threads')
      .update(updateData)
      .eq('thread_id', threadId)
      .select()
      .single();
  
    if (error) {
      console.error('Error updating thread:', error);
      throw new Error(`Error updating thread: ${error.message}`);
    }
  
    return updatedThread;
  };

export const toggleThreadPublicStatus = async (
    threadId: string,
    isPublic: boolean,
  ): Promise<Thread> => {
    return updateThread(threadId, { is_public: isPublic });
};

const deleteSandbox = async (sandboxId: string): Promise<void> => {
  try {
    const supabase = createClient();
    const {
      data: { session },
    } = await supabase.auth.getSession();

    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
    };

    if (session?.access_token) {
      headers['Authorization'] = `Bearer ${session.access_token}`;
    }

    const response = await fetch(`${API_URL}/sandboxes/${sandboxId}`, {
      method: 'DELETE',
      headers,
    });

    if (!response.ok) {
      console.warn('Failed to delete sandbox, continuing with thread deletion');
    }
  } catch (error) {
    console.warn('Error deleting sandbox, continuing with thread deletion:', error);
  }
};

export const deleteThread = async (threadId: string, sandboxId?: string): Promise<void> => {
    try {
      const supabase = createClient();

      // If sandbox ID is provided, delete it directly
      if (sandboxId) {
        await deleteSandbox(sandboxId);
      } else {
        // Otherwise, get the thread to find its project and sandbox
        const { data: thread, error: threadError } = await supabase
          .from('threads')
          .select('project_id')
          .eq('thread_id', threadId)
          .single();

        if (threadError) {
          console.error('Error fetching thread:', threadError);
          throw new Error(`Error fetching thread: ${threadError.message}`);
        }

        // If thread has a project, get sandbox ID and delete it
        if (thread?.project_id) {
          const { data: project } = await supabase
            .from('projects')
            .select('sandbox')
            .eq('project_id', thread.project_id)
            .single();

          if (project?.sandbox?.id) {
            await deleteSandbox(project.sandbox.id);
          }
        }
      }

      console.log(`Deleting all agent runs for thread ${threadId}`);
      const { error: agentRunsError } = await supabase
        .from('agent_runs')
        .delete()
        .eq('thread_id', threadId);

      if (agentRunsError) {
        console.error('Error deleting agent runs:', agentRunsError);
        throw new Error(`Error deleting agent runs: ${agentRunsError.message}`);
      }

      console.log(`Deleting all messages for thread ${threadId}`);
      const { error: messagesError } = await supabase
        .from('messages')
        .delete()
        .eq('thread_id', threadId);

      if (messagesError) {
        console.error('Error deleting messages:', messagesError);
        throw new Error(`Error deleting messages: ${messagesError.message}`);
      }

      console.log(`Deleting thread ${threadId}`);
      const { error: threadError2 } = await supabase
        .from('threads')
        .delete()
        .eq('thread_id', threadId);
  
      if (threadError2) {
        console.error('Error deleting thread:', threadError2);
        throw new Error(`Error deleting thread: ${threadError2.message}`);
      }
  
      console.log(
        `Thread ${threadId} successfully deleted with all related items`,
      );
    } catch (error) {
      console.error('Error deleting thread and related items:', error);
      throw error;
    }
  };
  

export const getPublicProjects = async (): Promise<Project[]> => {
    try {
      const supabase = createClient();
  
      // Query for threads that are marked as public
      const { data: publicThreads, error: threadsError } = await supabase
        .from('threads')
        .select('project_id')
        .eq('is_public', true);
  
      if (threadsError) {
        console.error('Error fetching public threads:', threadsError);
        return [];
      }
  
      // If no public threads found, return empty array
      if (!publicThreads?.length) {
        return [];
      }
  
      // Extract unique project IDs from public threads
      const publicProjectIds = [
        ...new Set(publicThreads.map((thread) => thread.project_id)),
      ].filter(Boolean);
  
      // If no valid project IDs, return empty array
      if (!publicProjectIds.length) {
        return [];
      }
  
      // Get the projects that have public threads
      const { data: projects, error: projectsError } = await supabase
        .from('projects')
        .select('*')
        .in('project_id', publicProjectIds);
  
      if (projectsError) {
        console.error('Error fetching public projects:', projectsError);
        return [];
      }
  
      console.log(
        '[API] Raw public projects from DB:',
        projects?.length,
        projects,
      );
  
      // Map database fields to our Project type
      const mappedProjects: Project[] = (projects || []).map((project) => ({
        id: project.project_id,
        name: project.name || '',
        description: project.description || '',
        account_id: project.account_id,
        created_at: project.created_at,
        updated_at: project.updated_at,
        sandbox: project.sandbox || {
          id: '',
          pass: '',
          vnc_preview: '',
          sandbox_url: '',
        },
        is_public: true, // Mark these as public projects
      }));
  
      console.log(
        '[API] Mapped public projects for frontend:',
        mappedProjects.length,
      );
  
      return mappedProjects;
    } catch (err) {
      console.error('Error fetching public projects:', err);
      return [];
    }
  };



  export const getProject = async (projectId: string): Promise<Project> => {
    const supabase = createClient();
  
    try {
      const { data, error } = await supabase
        .from('projects')
        .select('*')
        .eq('project_id', projectId)
        .single();
  
      if (error) {
        // Handle the specific "no rows returned" error from Supabase
        if (error.code === 'PGRST116') {
          throw new Error(`Project not found or not accessible: ${projectId}`);
        }
        throw error;
      }
  
      console.log('Raw project data from database:', data);
  
      // If project has a sandbox, ensure it's started
      if (data.sandbox?.id) {
        // Fire off sandbox activation without blocking
        const ensureSandboxActive = async () => {
          try {
            const {
              data: { session },
            } = await supabase.auth.getSession();
  
            // For public projects, we don't need authentication
            const headers: Record<string, string> = {
              'Content-Type': 'application/json',
            };
  
            if (session?.access_token) {
              headers['Authorization'] = `Bearer ${session.access_token}`;
            }
  
            console.log(`Ensuring sandbox is active for project ${projectId}...`);
            const response = await fetch(
              `${API_URL}/project/${projectId}/sandbox/ensure-active`,
              {
                method: 'POST',
                headers,
              },
            );
  
            if (!response.ok) {
              const errorText = await response
                .text()
                .catch(() => 'No error details available');
              console.warn(
                `Failed to ensure sandbox is active: ${response.status} ${response.statusText}`,
                errorText,
              );
            } else {
              console.log('Sandbox activation successful');
            }
          } catch (sandboxError) {
            console.warn('Failed to ensure sandbox is active:', sandboxError);
          }
        };
  
        // Start the sandbox activation without awaiting
        ensureSandboxActive();
      }
  
      // Map database fields to our Project type
      const mappedProject: Project = {
        id: data.project_id,
        name: data.name || '',
        description: data.description || '',
        account_id: data.account_id,
        is_public: data.is_public || false,
        created_at: data.created_at,
        sandbox: data.sandbox || {
          id: '',
          pass: '',
          vnc_preview: '',
          sandbox_url: '',
        },
      };
  
      // console.log('Mapped project data for frontend:', mappedProject);
  
      return mappedProject;
    } catch (error) {
      console.error(`Error fetching project ${projectId}:`, error);
      throw error;
    }
  };


  export const updateProject = async (
    projectId: string,
    data: Partial<Project>,
  ): Promise<Project> => {
    const supabase = createClient();
  
    console.log('Updating project with ID:', projectId);
    console.log('Update data:', data);
  
    // Sanity check to avoid update errors
    if (!projectId || projectId === '') {
      console.error('Attempted to update project with invalid ID:', projectId);
      throw new Error('Cannot update project: Invalid project ID');
    }
  
    const { data: updatedData, error } = await supabase
      .from('projects')
      .update(data)
      .eq('project_id', projectId)
      .select()
      .single();
  
    if (error) {
      console.error('Error updating project:', error);
      throw error;
    }
  
    if (!updatedData) {
      throw new Error('No data returned from update');
    }
  
    // Dispatch a custom event to notify components about the project change
    if (typeof window !== 'undefined') {
      window.dispatchEvent(
        new CustomEvent('project-updated', {
          detail: {
            projectId,
            updatedData: {
              id: updatedData.project_id,
              name: updatedData.name,
              description: updatedData.description,
            },
          },
        }),
      );
    }
  
    // Return formatted project data - use same mapping as getProject
    return {
      id: updatedData.project_id,
      name: updatedData.name,
      description: updatedData.description || '',
      account_id: updatedData.account_id,
      created_at: updatedData.created_at,
      sandbox: updatedData.sandbox || {
        id: '',
        pass: '',
        vnc_preview: '',
        sandbox_url: '',
      },
    };
  };