File size: 14,488 Bytes
f237798
 
 
 
 
 
6068938
f237798
 
 
 
 
 
 
 
 
6f30bfd
 
515e3fb
 
 
2ad2a62
f237798
6f30bfd
f237798
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48e10ef
f237798
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3689075
 
f237798
 
24502b8
f237798
 
 
14a92f0
 
 
 
 
 
 
f237798
 
 
14a92f0
 
 
 
 
f237798
 
 
48e10ef
f237798
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48e10ef
f237798
 
 
 
6068938
f237798
 
 
 
 
 
 
 
 
 
 
6068938
 
 
6800903
 
f237798
 
 
 
 
 
 
 
 
69f083f
 
f237798
 
 
 
 
 
 
 
 
 
 
 
 
 
69f083f
 
 
f237798
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6068938
f237798
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f30bfd
 
3689075
 
6f30bfd
 
3689075
6f30bfd
 
 
 
 
 
 
 
3689075
6f30bfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3689075
 
6f30bfd
3689075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f30bfd
3689075
 
6f30bfd
 
 
7087641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f30bfd
 
 
515e3fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f237798
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
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import type {
  AssessmentPackV2,
  AssessmentGenerationContextV2,
  AssessmentResultV2,
  AssessmentSubmissionV2,
  CertificateDetailsV2,
  CertificationTrack,
  HealthStatusV2,
  GeneratedCourseV2,
  GeneratedProjectV2,
  GitHubValidationReportV2,
  IssuedCertificateV2,
  PaymentRequestResponseV2,
  ProjectEvaluationV2,
  PublicProfileV2,
  SmartQuestionV2,
  FreeCourseItem,
  FreeCourseCompletionPayload,
  YtAnalyzeResponse,
  YtAssessmentStartResponse,
  YtAssessmentGradeResult,
} from '../types/getcertV2';
import { supabase } from './supabase';
import { DEFAULT_FREE_COURSES } from '../constants/defaultFreeCourses';

type ApiEnvelope<T> = {
  success: boolean;
  data?: T;
  error?: string;
  details?: unknown;
};

const API_BASE_URL = (import.meta.env.VITE_API_BASE_URL || '').trim().replace(/\/$/, '');

function parsePositiveTimeoutMs(value: unknown, fallbackMs: number): number {
  const parsed = Number(value);
  if (!Number.isFinite(parsed) || parsed <= 0) {
    return fallbackMs;
  }
  return Math.round(parsed);
}

const API_REQUEST_TIMEOUT_MS = parsePositiveTimeoutMs(import.meta.env.VITE_API_REQUEST_TIMEOUT_MS, 120000);

function normalizePath(path: string): string {
  return path.startsWith('/') ? path : `/${path}`;
}

function joinBaseAndPath(base: string, path: string): string {
  const normalizedPath = normalizePath(path);

  // Backward-compatible guard: if base already ends with /api and callers
  // pass /api/... paths, avoid constructing /api/api/...
  if (base.endsWith('/api') && normalizedPath.startsWith('/api/')) {
    return `${base}${normalizedPath.slice(4)}`;
  }

  return `${base}${normalizedPath}`;
}

function buildUrl(path: string): string {
  if (/^https?:\/\//i.test(path)) {
    return path;
  }

  if (!API_BASE_URL) {
    return normalizePath(path);
  }

  return joinBaseAndPath(API_BASE_URL, path);
}

function getNetworkErrorMessage(error: unknown): string {
  const message = error instanceof Error ? error.message : 'Unknown network error';
  return `Unable to reach API endpoint. ${message}. In local dev, run both frontend and API servers (npm run dev:full) or verify VITE_API_BASE_URL.`;
}

async function getAuthorizationHeader(): Promise<Record<string, string>> {
  try {
    const { data } = await supabase.auth.getSession();
    const accessToken = data.session?.access_token?.trim();

    if (!accessToken) {
      return {};
    }

    return { Authorization: `Bearer ${accessToken}` };
  } catch {
    return {};
  }
}

async function fetchWithTimeout(input: RequestInfo | URL, init: RequestInit = {}, timeoutMs = API_REQUEST_TIMEOUT_MS): Promise<Response> {
  const controller = new AbortController();
  const timeout = window.setTimeout(() => controller.abort(), timeoutMs);

  try {
    return await fetch(input, {
      ...init,
      signal: controller.signal,
    });
  } finally {
    window.clearTimeout(timeout);
  }
}

// No withFallback wrappers β€” all errors propagate to the UI for retry

async function parseResponse<T>(response: Response): Promise<T> {
  const raw = await response.text();
  let payload: ApiEnvelope<T> | null = null;

  if (raw) {
    try {
      payload = JSON.parse(raw) as ApiEnvelope<T>;
    } catch {
      payload = null;
    }
  }

  if (!response.ok) {
    if (payload?.error) {
      throw new Error(payload.error);
    }

    if (!payload) {
      throw new Error(
        `API ${response.status} returned non-JSON at ${response.url}. Run npm run dev:full or confirm VITE_API_BASE_URL.`
      );
    }

    throw new Error(`API request failed with status ${response.status}`);
  }

  if (!payload || !payload.success || payload.data === undefined) {
    throw new Error('API returned an unexpected response shape');
  }

  return payload.data;
}

async function postJson<T>(path: string, body: unknown): Promise<T> {
  let response: Response;
  try {
    const authorizationHeader = await getAuthorizationHeader();
    response = await fetchWithTimeout(buildUrl(path), {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', ...authorizationHeader },
      body: JSON.stringify(body),
    });
  } catch (error) {
    throw new Error(getNetworkErrorMessage(error));
  }

  return parseResponse<T>(response);
}

async function getJson<T>(path: string): Promise<T> {
  let response: Response;
  try {
    const authorizationHeader = await getAuthorizationHeader();
    response = await fetchWithTimeout(buildUrl(path), {
      method: 'GET',
      headers: { 'Content-Type': 'application/json', ...authorizationHeader },
    });
  } catch (error) {
    throw new Error(getNetworkErrorMessage(error));
  }

  return parseResponse<T>(response);
}

let clientCachedFreeCourses: FreeCourseItem[] | null = null;

export const getcertV2API = {
  generateCourse(skill: string): Promise<GeneratedCourseV2> {
    return postJson<GeneratedCourseV2>('/api/v2/course', { skill });
  },

  generateAssessment(skill: string, moduleTitles: string[], context?: AssessmentGenerationContextV2): Promise<AssessmentPackV2> {
    return postJson<AssessmentPackV2>('/api/v2/assessment', {
      mode: 'generate',
      skill,
      moduleTitles,
      courseSummary: context?.courseSummary,
      moduleContext: context?.modules,
    });
  },

  gradeAssessment(pack: AssessmentPackV2, submission: AssessmentSubmissionV2): Promise<AssessmentResultV2> {
    return postJson<AssessmentResultV2>('/api/v2/assessment', {
      mode: 'grade',
      pack,
      submission,
    });
  },

  generateProject(skill: string): Promise<GeneratedProjectV2> {
    return postJson<GeneratedProjectV2>('/api/v2/project', { skill });
  },

  validateGitHub(repoUrl: string): Promise<GitHubValidationReportV2> {
    return postJson<GitHubValidationReportV2>('/api/v2/github-validate', { repoUrl });
  },

  generateProjectQuestions(
    skill: string,
    url: string,
    retryCount = 0,
    isDesignProject = false
  ): Promise<{
    questions: SmartQuestionV2[];
    metadata: GitHubValidationReportV2['metadata'];
    validationSummary: {
      overallPassed: boolean;
      commitPassed: boolean;
      readmePassed: boolean;
    };
  }> {
    return postJson('/api/v2/project-questions', {
      skill,
      repoUrl: isDesignProject ? undefined : url,
      portfolioUrl: isDesignProject ? url : undefined,
      retryCount,
      isDesignProject,
    });
  },

  evaluateProject(payload: {
    skill: string;
    repoUrl?: string;
    projectType: 'web' | 'python' | 'data' | 'design';
    liveDemoUrl?: string;
    portfolioUrl?: string;
    notebookUrl?: string;
    questions: SmartQuestionV2[];
    answers: Array<{ questionId: string; answer: string }>;
  }): Promise<ProjectEvaluationV2> {
    return postJson<ProjectEvaluationV2>('/api/v2/project-evaluate', payload);
  },

  submitPaymentRequest(payload: {
    userId: string;
    txnId?: string;
    skill: string;
    projectTitle: string;
    githubUrl?: string;
    proofUrl: string;
    finalScore: number;
    scoreBreakdown?: ProjectEvaluationV2['scoreBreakdown'];
    validationSummary?: ProjectEvaluationV2['validationSummary'];
    projectType?: 'web' | 'python' | 'data' | 'design';
    commitCount?: number;
    liveDemoUrl?: string;
    paymentRequestId?: string;
    track?: CertificationTrack;
    email?: string;
    phone?: string;
    promoCode?: string;
    amountInr?: number;
  }): Promise<PaymentRequestResponseV2> {
    return postJson<PaymentRequestResponseV2>('/api/v2/payment-submit', payload);
  },

  getPaymentStatus(
    userId: string,
    paymentRequestId?: string,
    txnId?: string,
    skill?: string,
    projectTitle?: string,
    track?: string,
  ): Promise<PaymentRequestResponseV2> {
    const query = new URLSearchParams({ userId });
    if (paymentRequestId) {
      query.set('paymentRequestId', paymentRequestId);
    }
    if (txnId) {
      query.set('txnId', txnId);
    }
    if (skill) {
      query.set('skill', skill);
    }
    if (projectTitle) {
      query.set('projectTitle', projectTitle);
    }
    if (track) {
      query.set('track', track);
    }
    return getJson<PaymentRequestResponseV2>(
      `/api/v2/payment-status?${query.toString()}`
    );
  },

  certify(payload: {
    userId: string;
    name: string;
    email: string;
    skill: string;
    projectTitle: string;
    githubUrl?: string;
    proofUrl: string;
    finalScore: number;
    scoreBreakdown?: ProjectEvaluationV2['scoreBreakdown'];
    validationSummary?: ProjectEvaluationV2['validationSummary'];
    projectType?: 'web' | 'python' | 'data' | 'design';
    commitCount?: number;
    liveDemoUrl?: string;
    paymentRequestId?: string;
    txnId?: string;
    track?: CertificationTrack;
  }): Promise<IssuedCertificateV2> {
    return postJson<IssuedCertificateV2>('/api/v2/certify', payload);
  },

  getCertificate(certificateId: string): Promise<CertificateDetailsV2> {
    return getJson<CertificateDetailsV2>(`/api/v2/certificate/${encodeURIComponent(certificateId)}`);
  },

  getPublicProfile(userId: string): Promise<PublicProfileV2> {
    return getJson<PublicProfileV2>(`/api/v2/profile/${encodeURIComponent(userId)}`);
  },

  getHealth(): Promise<HealthStatusV2> {
    return getJson<HealthStatusV2>('/api/v2/health');
  },

  async getFreeCourses(): Promise<FreeCourseItem[]> {
    if (clientCachedFreeCourses && clientCachedFreeCourses.length > 0) {
      return clientCachedFreeCourses;
    }

    // 1. Direct Supabase query (Lightning fast: 30-50ms directly from Supabase, zero server cold-start)
    try {
      const { data, error } = await supabase
        .from('free_courses')
        .select('*')
        .eq('is_active', true)
        .order('display_order', { ascending: true });

      if (!error && data && data.length > 0) {
        const items = data.map((row: any) => {
          const videoId = row.youtube_video_id || 'kqtD5dpn9C8';
          const maxStudents = typeof row.max_students === 'number' && row.max_students > 0 ? row.max_students : null;
          const certifiedCount = typeof row.certified_students_count === 'number' ? row.certified_students_count : 0;
          return {
            id: row.id,
            courseId: row.course_id,
            title: row.title,
            skill: row.skill,
            description: row.description || '',
            category: row.category || 'Programming',
            level: row.level || 'Beginner',
            durationMinutes: row.duration_minutes || 30,
            maxStudents,
            certifiedStudentsCount: certifiedCount,
            isSoldOut: Boolean(maxStudents !== null && certifiedCount >= maxStudents),
            remainingSlots: maxStudents !== null ? Math.max(0, maxStudents - certifiedCount) : null,
            youtubeUrl: row.youtube_url || `https://www.youtube.com/watch?v=${videoId}`,
            youtubeVideoId: videoId,
            channelTitle: row.channel_title || 'Programming with Mosh',
            thumbnailUrl: row.thumbnail_url || `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`,
            embedUrl: `https://www.youtube-nocookie.com/embed/${videoId}?rel=0`,
            isActive: Boolean(row.is_active ?? true),
            displayOrder: row.display_order ?? 0,
            keyTakeaways: Array.isArray(row.key_takeaways) ? row.key_takeaways : [],
            quizQuestions: Array.isArray(row.quiz_questions) ? row.quiz_questions : [],
            createdAt: row.created_at,
            updatedAt: row.updated_at,
          };
        });
        clientCachedFreeCourses = items;
        return items;
      }
    } catch {
      // Supabase query error or table not yet migrated
    }

    // 2. Fast API probe with 2000ms timeout (never hang for 120s on sleeping containers)
    try {
      const controller = new AbortController();
      const timeout = setTimeout(() => controller.abort(), 2000);
      const url = buildUrl('/api/v2/free-courses');
      const response = await fetch(url, { signal: controller.signal });
      clearTimeout(timeout);
      if (response.ok) {
        const payload = await response.json();
        if (payload?.success && Array.isArray(payload.data?.courses) && payload.data.courses.length > 0) {
          clientCachedFreeCourses = payload.data.courses;
          return payload.data.courses;
        }
      }
    } catch {
      // Backend cold starting or unreachable
    }

    // 3. Instant local fallback (0ms)
    clientCachedFreeCourses = DEFAULT_FREE_COURSES;
    return DEFAULT_FREE_COURSES;
  },

  async updateFreeCourseProgress(payload: {
    courseId: string;
    courseTitle: string;
    progressPercentage?: number;
    currentStep?: string;
    status?: string;
    score?: number;
  }): Promise<{ success: boolean }> {
    try {
      return await postJson<{ success: boolean }>('/api/v2/free-courses/progress', payload);
    } catch {
      return { success: false };
    }
  },

  completeFreeCourse(payload: FreeCourseCompletionPayload): Promise<IssuedCertificateV2> {
    return postJson<IssuedCertificateV2>('/api/v2/free-courses/complete', payload);
  },

  // ─── GetCert YT ("Certify Your Learning from YouTube") ─────────────────────
  analyzeYouTubeCourse(url: string): Promise<YtAnalyzeResponse> {
    return postJson<YtAnalyzeResponse>('/api/v2/yt/analyze', { url });
  },

  startYtAssessment(snapshotId: string): Promise<YtAssessmentStartResponse> {
    return postJson<YtAssessmentStartResponse>('/api/v2/yt/assessment/start', { snapshotId });
  },

  submitYtAssessment(payload: {
    snapshotId: string;
    attemptId: string;
    answers: Record<string, number>;
  }): Promise<YtAssessmentGradeResult> {
    return postJson<YtAssessmentGradeResult>('/api/v2/yt/assessment/submit', payload);
  },

  checkoutYtCertification(payload: {
    snapshotId: string;
    score: number;
    email?: string;
  }): Promise<{
    paywallEnabled: boolean;
    amountInr: number;
    checkoutUrl: string;
    checkoutId: string;
    paymentSessionId: string;
    track: string;
    message: string;
  }> {
    return postJson('/api/v2/yt/checkout', payload);
  },

  certifyYtCourse(payload: {
    userId: string;
    name: string;
    email: string;
    skill: string;
    projectTitle: string;
    finalScore: number;
    paymentRequestId?: string;
    txnId?: string;
    track: 'ytcert';
    extraMetadata?: Record<string, any>;
  }): Promise<IssuedCertificateV2> {
    return postJson<IssuedCertificateV2>('/api/v2/certify', payload);
  },
};