const { Pool } = require('pg');
const dbPool = new Pool({
  connectionString: process.env.DATABASE_URL || 'postgresql://postgres:postgres@localhost:5432/postgres'
});

async function test() {
  try {
    const crianca = 'Maria';
    let sql = `
      SELECT date, time, report, criancas, tags 
      FROM escola.observacoes 
      WHERE 1=1
    `;
    const params = [];
    let pCount = 1;

    if (crianca && crianca !== 'todas') {
      sql += ` AND (
        (jsonb_typeof(criancas) = 'array' AND EXISTS (
          SELECT 1 FROM jsonb_array_elements_text(criancas) AS c 
          WHERE LOWER(c) LIKE $${pCount}
        ))
        OR criancas IS NULL
      )`;
      params.push(`%${crianca.toLowerCase()}%`);
      pCount++;
    }

    sql += ` ORDER BY date ASC`;
    const dbRes = await dbPool.query(sql, params);
    console.log('Quantidade de observações:', dbRes.rows.length);
    console.log('Linhas:', dbRes.rows.map(r => ({ date: r.date, criancas: r.criancas })));
  } catch (err) {
    console.error(err);
  } finally {
    await dbPool.end();
  }
}

test();
