import pg from 'pg';
import dotenv from 'dotenv';
dotenv.config();

const pool = new pg.Pool({
  user: process.env.POSTGRES_USER || 'edumanager',
  host: process.env.POSTGRES_HOST || '150.230.87.131',
  database: process.env.POSTGRES_DB || 'edumanager',
  password: process.env.POSTGRES_PASSWORD,
  port: process.env.POSTGRES_PORT || 5432,
});

async function run() {
  try {
    const res = await pool.query(`
      WITH RankedRecords AS (
          SELECT 
              id,
              ROW_NUMBER() OVER (
                  PARTITION BY aluno_id, COALESCE(aula_id, data::date::text)
                  ORDER BY 
                      CASE 
                          WHEN tipo = 'absence' AND justificativa IS NOT NULL THEN 1
                          WHEN tipo = 'presence' THEN 2
                          WHEN tipo = 'absence' AND justificativa IS NULL THEN 3
                          ELSE 4 
                      END ASC,
                      created_at DESC
              ) as rn
          FROM frequencias
      )
      DELETE FROM frequencias WHERE id IN (SELECT id FROM RankedRecords WHERE rn > 1);
    `);
    console.log('Duplicatas deletadas:', res.rowCount);
  } catch (err) {
    console.error('Erro:', err);
  } finally {
    pool.end();
  }
}

run();
