import pg from 'pg';

const DATABASE_URL = 'postgresql://edumanager:EduManager2026!Seguro@150.230.87.131:5432/edumanager';
const pool = new pg.Pool({ connectionString: DATABASE_URL });

async function migrate() {
  try {
    console.log('--- MIGRATING CONFIGURAÇÕES TO SQL ---');
    
    // 1. Get school data
    const { rows: sdRows } = await pool.query('SELECT data FROM school_data WHERE id = 1');
    if (sdRows.length === 0 || !sdRows[0].data) {
      console.log('No legacy school_data found.');
      return;
    }
    
    const data = sdRows[0].data;
    console.log('Legacy school_data loaded successfully.');

    // 2. Perform insert/sync into configuracoes table
    if (data.profiles && Array.isArray(data.profiles) && data.profiles.length > 0) {
      console.log(`Found ${data.profiles.length} profiles in legacy JSON. Syncing...`);
      
      const profileIds = data.profiles.map(p => p.id).filter(Boolean);
      await pool.query('DELETE FROM configuracoes WHERE id != ALL($1)', [profileIds]);

      for (const p of data.profiles) {
        if (!p.id || !p.name) continue;
        await pool.query(
          `INSERT INTO configuracoes (
            id, nome, endereco, cidade, estado, cep, cnpj, telefone, email, tipo,
            logo, evolution_api_url, evolution_instance_name, evolution_api_key,
            message_templates, updated_at
          ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, NOW())
          ON CONFLICT (id) DO UPDATE SET
            nome = EXCLUDED.nome, endereco = EXCLUDED.endereco, cidade = EXCLUDED.cidade,
            estado = EXCLUDED.estado, cep = EXCLUDED.cep, cnpj = EXCLUDED.cnpj,
            telefone = EXCLUDED.telefone, email = EXCLUDED.email, tipo = EXCLUDED.tipo,
            logo = EXCLUDED.logo, evolution_api_url = EXCLUDED.evolution_api_url,
            evolution_instance_name = EXCLUDED.evolution_instance_name, evolution_api_key = EXCLUDED.evolution_api_key,
            message_templates = EXCLUDED.message_templates, updated_at = NOW()`,
          [
            p.id, p.name, p.address || '', p.city || '', p.state || '', p.zip || '', p.cnpj || '', p.phone || '', p.email || '', p.type || 'filial',
            data.logo || '',
            data.evolutionConfig?.apiUrl || '',
            data.evolutionConfig?.instanceName || '',
            data.evolutionConfig?.apiKey || '',
            data.messageTemplates ? JSON.stringify(data.messageTemplates) : null
          ]
        );
        console.log(`Synced profile: ${p.name} (${p.type})`);
      }
    } else if (data.profile) {
      console.log('Found single profile in legacy JSON. Syncing...');
      const p = data.profile;
      await pool.query(
        `INSERT INTO configuracoes (
          id, nome, endereco, cidade, estado, cep, cnpj, telefone, email, tipo,
          logo, evolution_api_url, evolution_instance_name, evolution_api_key,
          message_templates, updated_at
        ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, NOW())
        ON CONFLICT (id) DO UPDATE SET
          nome = EXCLUDED.nome, endereco = EXCLUDED.endereco, cidade = EXCLUDED.cidade,
          estado = EXCLUDED.estado, cep = EXCLUDED.cep, cnpj = EXCLUDED.cnpj,
          telefone = EXCLUDED.telefone, email = EXCLUDED.email, tipo = EXCLUDED.tipo,
          logo = EXCLUDED.logo, evolution_api_url = EXCLUDED.evolution_api_url,
          evolution_instance_name = EXCLUDED.evolution_instance_name, evolution_api_key = EXCLUDED.evolution_api_key,
          message_templates = EXCLUDED.message_templates, updated_at = NOW()`,
        [
          p.id || 'main-school', p.name, p.address || '', p.city || '', p.state || '', p.zip || '', p.cnpj || '', p.phone || '', p.email || '', p.type || 'matriz',
          data.logo || '',
          data.evolutionConfig?.apiUrl || '',
          data.evolutionConfig?.instanceName || '',
          data.evolutionConfig?.apiKey || '',
          data.messageTemplates ? JSON.stringify(data.messageTemplates) : null
        ]
      );
      console.log(`Synced single profile: ${p.name}`);
    } else {
      console.log('No profiles found in legacy JSON to migrate.');
    }

    // Double check contents of SQL table
    const { rows: checkRows } = await pool.query('SELECT id, nome, tipo, logo FROM configuracoes');
    console.log('SQL TABLE CONTENTS AFTER MIGRATION:', checkRows);
    
    console.log('--- MIGRATION COMPLETED SUCCESSFULLY ---');
  } catch (err) {
    console.error('Migration failed:', err.message);
  } finally {
    await pool.end();
  }
}

migrate();
