const { Pool } = require('pg');

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

async function run() {
  const client = await pool.connect();
  try {
    const res = await client.query(`
      DELETE FROM frequencias a
      WHERE a.tipo = 'absence' AND a.id LIKE 'auto-abs-%'
      AND EXISTS (
          SELECT 1 FROM frequencias p
          WHERE p.tipo = 'presence'
          AND p.aluno_id = a.aluno_id
          AND (p.aula_id = a.aula_id OR DATE(p.data AT TIME ZONE 'UTC') = DATE(a.data AT TIME ZONE 'UTC'))
      ) RETURNING id;
    `);
    console.log(`Deleted ${res.rowCount} orphaned absences.`);
  } catch (err) {
    console.error(err);
  } finally {
    client.release();
    pool.end();
  }
}

run();
