import { createClient } from '@supabase/supabase-js'; const SUPABASE_URL = process.env.SUPABASE_URL || 'https://hwithddwaapyhnfwcesj.supabase.co'; const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY; const supabase = createClient(SUPABASE_URL, SUPABASE_KEY); export default async function handler(req, res) { if (!SUPABASE_KEY) return res.status(500).json({ error: 'Service key missing' }); try { console.log('Starting migration to shift indices...'); // 1. Migrate 'products' table const { data: products } = await supabase .from('products') .select('product_id, data') .eq('status', 'edited'); // Only migrated ones need shifting let pCount = 0; if (products) { for (const p of products) { if (p.data.length >= 13 && (typeof p.data[12] === 'number' || (typeof p.data[12] === 'string' && /^[0-9.]+$/.test(p.data[12])))) { const newData = [...p.data]; newData.splice(12, 0, ''); // Insert empty PM Classification await supabase.from('products').update({ data: newData }).eq('product_id', p.product_id); pCount++; } } } // 2. Migrate 'products_history' table (optional but good for consistency) const { data: history } = await supabase .from('products_history') .select('id, old_data, new_data'); let hCount = 0; if (history) { for (const h of history) { let changed = false; let nOld = h.old_data; let nNew = h.new_data; if (nOld && nOld.length >= 13 && (typeof nOld[12] === 'number' || (typeof nOld[12] === 'string' && /^[0-9.]+$/.test(nOld[12])))) { nOld = [...nOld]; nOld.splice(12, 0, ''); changed = true; } if (nNew && nNew.length >= 13 && (typeof nNew[12] === 'number' || (typeof nNew[12] === 'string' && /^[0-9.]+$/.test(nNew[12])))) { nNew = [...nNew]; nNew.splice(12, 0, ''); changed = true; } if (changed) { await supabase.from('products_history').update({ old_data: nOld, new_data: nNew }).eq('id', h.id); hCount++; } } } return res.json({ success: true, productsMigrated: pCount, historyMigrated: hCount, message: 'Migration completed successfully. Indices >= 12 shifted by +1.' }); } catch (err) { return res.status(500).json({ error: err.message }); } }