const fs = require('fs');
const { createClient } = require('@supabase/supabase-js');

// Parse .env.local
const envFile = fs.readFileSync('.env.local', 'utf8');
const envVars = {};
envFile.split('\n').forEach(line => {
  const match = line.match(/^([^=]+)=(.*)$/);
  if (match) envVars[match[1]] = match[2];
});

async function main() {
  const supabaseUrl = envVars.NEXT_PUBLIC_SUPABASE_URL;
  const supabaseKey = envVars.SUPABASE_SERVICE_ROLE_KEY;

  if (!supabaseUrl || !supabaseKey) {
    console.error('Missing Supabase credentials in .env.local');
    process.exit(1);
  }

  const supabase = createClient(supabaseUrl, supabaseKey);

  // 1. Upload Sub-districts
  console.log('Reading GeoJSON...');
  const geojsonRaw = fs.readFileSync('src/lib/Admin_Kecamatan.json', 'utf8');
  const geojson = JSON.parse(geojsonRaw);

  for (const feature of geojson.features) {
    const name = feature.properties?.Ket;
    if (!name) continue;

    let geom = feature.geometry;
    if (geom.type === 'Polygon') {
      geom = {
        type: 'MultiPolygon',
        coordinates: [geom.coordinates]
      };
    }

    console.log(`Uploading ${name}...`);
    // Supabase auto-casts GeoJSON objects to PostGIS geometry during insert
    const { error } = await supabase.from('sub_districts').upsert(
      { name: name, geom: geom },
      { onConflict: 'name' }
    );

    if (error) {
      console.error(`Failed to upload ${name}:`, error.message);
    } else {
      console.log(`Success: ${name}`);
    }
  }

  // 2. Trigger updates on existing households to populate the sub_district column
  console.log('Triggering updates on existing households to populate sub_district...');
  const { data: households, error: fetchErr } = await supabase.from('households').select('id, location');
  
  if (fetchErr) {
    console.error('Error fetching households:', fetchErr);
  } else if (households && households.length > 0) {
    console.log(`Found ${households.length} households. Updating...`);
    for (const hh of households) {
      // Touching the row will fire the trigger
      const { error: upErr } = await supabase.from('households').update({ location: hh.location }).eq('id', hh.id);
      if (upErr) console.error(`Error updating HH ${hh.id}:`, upErr.message);
    }
    console.log('Completed household updates.');
  } else {
    console.log('No households found to update.');
  }

  console.log('Migration complete.');
}

main();
