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 });

const formatDateForJSON = (val) => {
  if (!val) return '';
  if (val instanceof Date) {
    return val.toISOString().substring(0, 10);
  }
  if (typeof val === 'string') {
    return val.substring(0, 10);
  }
  return '';
};

async function testSync() {
  try {
    console.log('--- TESTING REVERSE SYNC FOR TURMAS ---');
    
    // Fetch from Postgres
    const { rows: dbTurmas } = await pool.query('SELECT * FROM turmas ORDER BY nome ASC');
    console.log(`Found ${dbTurmas.length} classes in SQL.`);

    // Fetch school data
    const { rows: sdRows } = await pool.query('SELECT data FROM school_data WHERE id = 1');
    const appData = sdRows[0].data;

    // Map
    appData.classes = dbTurmas.map((t) => ({
      id: t.id,
      name: t.nome,
      courseId: t.curso_id,
      teacher: t.professor,
      schedule: t.horario,
      scheduleDay: t.dia_semana,
      maxStudents: Number(t.max_alunos || 0),
      startDate: formatDateForJSON(t.data_inicio),
      endDate: formatDateForJSON(t.data_fim),
      defaultStartTime: t.horario_inicio_padrao,
      defaultEndTime: t.horario_fim_padrao
    }));
    appData.lastUpdated = new Date().toISOString();

    // Save
    await pool.query(
      'UPDATE school_data SET data = $1, updated_at = NOW() WHERE id = 1',
      [JSON.stringify(appData)]
    );
    
    console.log('--- REVERSE SYNC SUCCESSFUL ---');
  } catch (err) {
    console.error('ERROR:', err.message);
  } finally {
    await pool.end();
  }
}

testSync();
