|
| 1 | +import { NextRequest, NextResponse } from 'next/server' |
| 2 | +import { createClient as createServiceClient } from '@supabase/supabase-js' |
| 3 | + |
| 4 | +export async function POST(request: NextRequest) { |
| 5 | + try { |
| 6 | + const { testId, userId, userEmail, userMetadata } = await request.json() |
| 7 | + |
| 8 | + if (!testId || !userId) { |
| 9 | + return NextResponse.json( |
| 10 | + { error: 'Test ID and User ID are required' }, |
| 11 | + { status: 400 } |
| 12 | + ) |
| 13 | + } |
| 14 | + |
| 15 | + // Use service role client to bypass RLS |
| 16 | + const serviceSupabase = createServiceClient( |
| 17 | + process.env.NEXT_PUBLIC_SUPABASE_URL!, |
| 18 | + process.env.SUPABASE_SERVICE_ROLE_KEY! |
| 19 | + ) |
| 20 | + |
| 21 | + // Check if already registered |
| 22 | + const { data: existingRegistration } = await serviceSupabase |
| 23 | + .from('test_registrations') |
| 24 | + .select('id') |
| 25 | + .eq('test_id', testId) |
| 26 | + .eq('user_id', userId) |
| 27 | + .single() |
| 28 | + |
| 29 | + if (existingRegistration) { |
| 30 | + return NextResponse.json( |
| 31 | + { error: 'User is already registered for this test' }, |
| 32 | + { status: 400 } |
| 33 | + ) |
| 34 | + } |
| 35 | + |
| 36 | + // Ensure profile exists to prevent trigger failure |
| 37 | + try { |
| 38 | + const { error: profileError } = await serviceSupabase |
| 39 | + .from('profiles') |
| 40 | + .select('id, first_name, last_name, email') |
| 41 | + .eq('id', userId) |
| 42 | + .single() |
| 43 | + |
| 44 | + if (profileError && profileError.code === 'PGRST116') { |
| 45 | + // Profile doesn't exist, create a minimal one |
| 46 | + const { error: createError } = await serviceSupabase |
| 47 | + .from('profiles') |
| 48 | + .insert({ |
| 49 | + id: userId, |
| 50 | + email: userEmail, |
| 51 | + first_name: userMetadata?.first_name || userMetadata?.given_name || '', |
| 52 | + last_name: userMetadata?.last_name || userMetadata?.family_name || '', |
| 53 | + is_public: true, |
| 54 | + email_notifications: true, |
| 55 | + profile_completion_percentage: 0, |
| 56 | + is_admin: false, |
| 57 | + username_editable: true, |
| 58 | + username_set: false, |
| 59 | + profile_complete: false |
| 60 | + }) |
| 61 | + |
| 62 | + if (createError) { |
| 63 | + console.error('Error creating profile:', createError) |
| 64 | + // Continue anyway, the trigger might still work |
| 65 | + } |
| 66 | + } |
| 67 | + } catch (profileException) { |
| 68 | + console.error('Exception during profile check/creation:', profileException) |
| 69 | + // Continue with registration |
| 70 | + } |
| 71 | + |
| 72 | + // Prepare registration data with proper fallbacks for the trigger |
| 73 | + const fullName = userMetadata?.full_name || |
| 74 | + userMetadata?.name || |
| 75 | + (userMetadata?.first_name && userMetadata?.last_name ? |
| 76 | + `${userMetadata.first_name} ${userMetadata.last_name}` : |
| 77 | + null); |
| 78 | + |
| 79 | + // Register for the test |
| 80 | + const { data, error } = await serviceSupabase |
| 81 | + .from('test_registrations') |
| 82 | + .insert([{ |
| 83 | + test_id: testId, |
| 84 | + user_id: userId, |
| 85 | + status: 'registered', |
| 86 | + attempt_count: 0, |
| 87 | + registration_date: new Date().toISOString(), |
| 88 | + full_name: fullName, |
| 89 | + email: userEmail || null, |
| 90 | + phone: null, |
| 91 | + institution: null, |
| 92 | + department: null, |
| 93 | + year_of_study: null, |
| 94 | + experience_level: null, |
| 95 | + registration_data: { |
| 96 | + registered_via: 'api_tests_register', |
| 97 | + registration_timestamp: new Date().toISOString(), |
| 98 | + user_metadata: userMetadata |
| 99 | + } |
| 100 | + }]) |
| 101 | + .select() |
| 102 | + |
| 103 | + if (error) { |
| 104 | + console.error('Registration error:', error) |
| 105 | + return NextResponse.json( |
| 106 | + { error: 'Failed to register for test', details: error.message }, |
| 107 | + { status: 500 } |
| 108 | + ) |
| 109 | + } |
| 110 | + |
| 111 | + return NextResponse.json({ |
| 112 | + success: true, |
| 113 | + data: data[0] |
| 114 | + }) |
| 115 | + |
| 116 | + } catch (error) { |
| 117 | + console.error('Error in test registration API:', error) |
| 118 | + return NextResponse.json( |
| 119 | + { error: 'Internal server error' }, |
| 120 | + { status: 500 } |
| 121 | + ) |
| 122 | + } |
| 123 | +} |
0 commit comments