import { createClient } from '@supabase/supabase-js'; import { readFileSync } from 'fs'; import * as path from 'path'; import * as dotenv from 'dotenv'; import { existsSync } from 'fs'; import { fileURLToPath } from 'url'; // Get the current file's directory path in ESM const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Load environment variables from .env.local const envLocalPath = path.resolve(process.cwd(), '.env.local'); if (existsSync(envLocalPath)) { console.log(`Loading environment from: ${envLocalPath}`); dotenv.config({ path: envLocalPath }); } else { console.log(`No .env.local file found at: ${envLocalPath}`); dotenv.config(); // Try loading from default .env } interface FAQ { id: number; question: string; answer: string; } async function seedFaqs() { console.log('Starting FAQ seeding process...'); // Initialize Supabase client const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseServiceKey) { console.error('Missing Supabase environment variables. Please set NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.'); process.exit(1); } console.log(`Using Supabase URL: ${supabaseUrl}`); // Create Supabase client const supabase = createClient(supabaseUrl, supabaseServiceKey, { auth: { autoRefreshToken: false, persistSession: false } }); try { // Read FAQ data const faqDataPath = path.join(process.cwd(), 'src/data/faq.json'); console.log(`Reading FAQ data from: ${faqDataPath}`); if (!existsSync(faqDataPath)) { console.error(`FAQ data file not found at: ${faqDataPath}`); process.exit(1); } const faqData = JSON.parse(readFileSync(faqDataPath, 'utf-8')) as FAQ[]; console.log(`Found ${faqData.length} FAQs to process`); // Verify the table exists console.log('Checking if faqs table exists...'); const { error: tableError } = await supabase .from('faqs') .select('id') .limit(1); if (tableError) { console.error('Error accessing faqs table:', tableError); console.error('Please make sure the faqs table has been created with the correct structure.'); process.exit(1); } console.log('Successfully connected to faqs table'); // Option to delete existing records if (process.argv.includes('--clean')) { console.log('Cleaning existing FAQ records...'); const { error: deleteError } = await supabase .from('faqs') .delete() .neq('id', 0); if (deleteError) { console.error('Error deleting existing FAQs:', deleteError); } else { console.log('Successfully deleted existing FAQs'); } } // Process each FAQ console.log('Beginning to process FAQs...'); let successful = 0; let failed = 0; for (const faq of faqData) { console.log(`Processing FAQ ID ${faq.id}: "${faq.question.substring(0, 30)}..."`); // First check if it exists const { data: existingFaq, error: checkError } = await supabase .from('faqs') .select('id') .eq('id', faq.id) .single(); // "No rows found" is expected when the FAQ doesn't exist yet, so we treat it as non-existent if (checkError && !checkError.message.includes('No rows found') && !checkError.details?.includes('contains 0 rows')) { console.error(`Error checking for FAQ ID ${faq.id}:`, checkError); failed++; continue; } // Prepare the data to insert or update const faqRecord = { id: faq.id, question: faq.question, answer: faq.answer, updated_at: new Date().toISOString() }; // If no error or a "No rows found" error, determine whether to update or insert if (existingFaq) { // Update existing console.log(`Updating existing FAQ ID ${faq.id}`); const { error: updateError } = await supabase .from('faqs') .update(faqRecord) .eq('id', faq.id); if (updateError) { console.error(`Failed to update FAQ ID ${faq.id}:`, updateError); failed++; } else { console.log(`Successfully updated FAQ ID ${faq.id}`); successful++; } } else { // Insert new - this will happen when checkError indicates no rows were found console.log(`Inserting new FAQ ID ${faq.id}`); const { error: insertError } = await supabase .from('faqs') .insert({ ...faqRecord, created_at: new Date().toISOString() }); if (insertError) { console.error(`Failed to insert FAQ ID ${faq.id}:`, insertError); failed++; } else { console.log(`Successfully inserted FAQ ID ${faq.id}`); successful++; } } } // Final summary console.log('\n===== FAQ SEEDING SUMMARY ====='); console.log(`Total FAQs: ${faqData.length}`); console.log(`Successfully processed: ${successful}`); console.log(`Failed: ${failed}`); console.log('==============================='); if (successful > 0) { console.log('FAQ seeding completed with some success!'); } else { console.error('FAQ seeding completed with no successful entries.'); process.exit(1); } } catch (error) { console.error('Unexpected error during FAQ seeding:', error); process.exit(1); } } // Run the seeding function seedFaqs() .then(() => { console.log('FAQ seeding script completed.'); process.exit(0); }) .catch((error) => { console.error('Error in FAQ seeding script:', error); process.exit(1); });