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 || 'sb_publishable_fGXkh0bSrAOqSk2jWKAzSg_NJD9YPCv';

const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);

export default async function handler(req, res) {
  try {
    console.log('Starting migration v3...');
    
    // 1. Fetch products
    const { data: products, error: pErr } = await supabase
      .from('products')
      .select('product_id, data')
      .in('status', ['edited', 'synced', 'pending']);
    
    if (pErr) return res.status(500).json({ error: 'Fetch products failed', details: pErr });

    let pCount = 0;
    if (products && products.length > 0) {
      for (const p of products) {
        const oldData = p.data;
        if (!oldData || oldData.length < 13) continue;

        const valAt12 = oldData[12];
        const isOld = typeof valAt12 === 'number' || (typeof valAt12 === 'string' && /^[0-9.]+$/.test(valAt12));
        
        if (isOld && oldData.length < 110) {
          const newData = [...oldData];
          newData.splice(12, 0, ''); 
          const { error: updateErr } = await supabase.from('products').update({ data: newData }).eq('product_id', p.product_id);
          if (!updateErr) pCount++;
        }
      }
    }

    // 2. History
    const { data: history, error: hErr } = await supabase.from('products_history').select('*');
    if (hErr) return res.status(500).json({ error: 'Fetch history failed', details: hErr });
    
    let hCount = 0;
    if (history && history.length > 0) {
      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) {
          const { error: histErr } = await supabase.from('products_history').update({ old_data: nOld, new_data: nNew }).eq('id', h.id);
          if (!histErr) hCount++;
        }
      }
    }

    return res.json({
      success: true,
      productsMigrated: pCount,
      historyMigrated: hCount,
      message: 'Migration v3 finished.'
    });
  } catch (err) {
    return res.status(500).json({ error: err.message });
  }
}
