import { createClient } from '@supabase/supabase-js'; import * as dotenv from 'dotenv'; import path from 'path'; import { fileURLToPath } from 'url'; import fs from 'fs'; // Load environment variables from .env file const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); dotenv.config({ path: path.resolve(__dirname, '../.env') }); // Read the .env file directly as a fallback const envPath = path.resolve(__dirname, '../.env'); const envContent = fs.readFileSync(envPath, 'utf8'); const envVars = envContent.split('\n').reduce((acc, line) => { const match = line.match(/^([^#=]+)=(.*)$/); if (match) { const key = match[1].trim(); const value = match[2].trim().replace(/^["']|["']$/g, ''); // Remove quotes if present acc[key] = value; } return acc; }, {} as Record); // Set environment variables if not already set if (!process.env.NEXT_PUBLIC_SUPABASE_URL) { process.env.NEXT_PUBLIC_SUPABASE_URL = envVars.NEXT_PUBLIC_SUPABASE_URL; } if (!process.env.SUPABASE_SERVICE_ROLE_KEY) { process.env.SUPABASE_SERVICE_ROLE_KEY = envVars.SUPABASE_SERVICE_ROLE_KEY; } // Create a Supabase client with the service role key const createServiceClient = () => { const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || envVars.NEXT_PUBLIC_SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || envVars.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseServiceKey) { console.error('Missing Supabase environment variables for service client.'); throw new Error('Missing Supabase environment variables for service client'); } return createClient(supabaseUrl, supabaseServiceKey, { auth: { persistSession: false, } }); }; async function seedCategories() { const supabase = createServiceClient(); console.log('Supabase client created successfully'); // Get categories from the JSON file const categoriesPath = path.resolve(__dirname, '../src/data/categories.json'); const categories = JSON.parse(fs.readFileSync(categoriesPath, 'utf8')); // Get news from the JSON file const newsPath = path.resolve(__dirname, '../src/data/news.json'); const newsItems = JSON.parse(fs.readFileSync(newsPath, 'utf8')); console.log(`Loaded ${categories.length} categories and ${newsItems.length} news items from JSON files`); // Get all existing categories with their IDs, slugs, and icons const { data: existingCategories, error: fetchError } = await supabase .from('categories') .select('id, name, slug, icon'); if (fetchError) { console.error('Error fetching existing categories:', fetchError); throw fetchError; } console.log(`Found ${existingCategories?.length || 0} existing categories in the database`); // Create a map of existing categories by ID const categoriesById = new Map(); existingCategories?.forEach(cat => { if (cat.id) categoriesById.set(cat.id, cat); }); // Process each news item console.log('Processing news items...'); let processedCount = 0; // Check if --all flag is provided to process all news items const processAllItems = process.argv.includes('--all'); const itemsToProcess = processAllItems ? newsItems : newsItems.slice(0, 5); // Process only the first 5 for testing unless --all is specified for (const newsItem of itemsToProcess) { try { // Check if the news item already exists by URL - use select() instead of maybeSingle() const { data: existingNewsItems, error: checkError } = await supabase .from('news') .select('id, title, url') .ilike('url', `%${newsItem.url.replace(/https?:\/\//, '')}%`); if (checkError) { console.error(`Error checking for existing news item ${newsItem.title}:`, checkError); continue; } let newsId: string; if (existingNewsItems && existingNewsItems.length > 0) { // Use the first matching news item const existingNews = existingNewsItems[0]; console.log(`News item "${newsItem.title}" already exists with ID ${existingNews.id}, updating...`); newsId = existingNews.id; // Update the existing news item const { error: updateError } = await supabase .from('news') .update({ title: newsItem.title, content: newsItem.summary, image_url: newsItem.imageUrl || '', source: newsItem.source, article_date: new Date(newsItem.date).toISOString(), updated_at: new Date().toISOString() }) .eq('id', newsId); if (updateError) { console.error(`Error updating news item ${newsItem.title}:`, updateError); continue; } // Delete existing category relationships const { error: deleteError } = await supabase .from('news_categories') .delete() .eq('news_id', newsId); if (deleteError) { console.error(`Error deleting existing categories for news item ${newsItem.title}:`, deleteError); } } else { // Create new news item const { data: createdNews, error: createError } = await supabase .from('news') .insert({ title: newsItem.title, content: newsItem.summary, url: newsItem.url, image_url: newsItem.imageUrl || '', source: newsItem.source, article_date: new Date(newsItem.date).toISOString(), created_at: new Date().toISOString(), updated_at: new Date().toISOString() }) .select() .single(); if (createError) { console.error(`Error creating news item ${newsItem.title}:`, createError); continue; } newsId = createdNews.id; console.log(`Created news item "${newsItem.title}" with ID ${newsId}`); } // Add primary category relationship if (newsItem.primary_category_id) { const primaryCategory = categoriesById.get(newsItem.primary_category_id); if (primaryCategory) { const { error: primaryCatError } = await supabase .from('news_categories') .insert({ news_id: newsId, category_id: primaryCategory.id, is_primary: true }); if (primaryCatError) { console.error(`Error adding primary category to news item ${newsItem.title}:`, primaryCatError); } else { console.log(`Added primary category ${primaryCategory.name} to news item "${newsItem.title}"`); } } else { console.warn(`Primary category ID ${newsItem.primary_category_id} not found for news item ${newsItem.title}`); } } // Add secondary category relationships if (newsItem.categories && newsItem.categories.length > 0) { for (const categoryId of newsItem.categories) { // Skip if this is the same as the primary category if (categoryId === newsItem.primary_category_id) continue; const category = categoriesById.get(categoryId); if (category) { const { error: secondaryCatError } = await supabase .from('news_categories') .insert({ news_id: newsId, category_id: category.id, is_primary: false }); if (secondaryCatError) { console.error(`Error adding secondary category ${categoryId} to news item ${newsItem.title}:`, secondaryCatError); } else { console.log(`Added secondary category ${category.name} to news item "${newsItem.title}"`); } } else { console.warn(`Secondary category ID ${categoryId} not found for news item ${newsItem.title}`); } } } processedCount++; console.log(`Successfully processed news item: ${newsItem.title}`); } catch (error) { console.error(`Error processing news item ${newsItem.title}:`, error); } } console.log(`News items seeding completed. Processed ${processedCount} items.`); } // Run the test seedCategories() .then(() => { console.log('Test script completed'); process.exit(0); }) .catch(error => { console.error('Test script failed:', error); process.exit(1); });