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

async function main() {
  const conn = new Client({
    host: 'localhost',
    port: 5432,
    user: 'postgres',
    password: 'turbo123',
    database: 'genome_db'
  });
  await conn.connect();

  const farmNo = 1;

  // 농가 내 모든 개체의 선발지수(가중 합계) 조회
  const farmCowsResult = await conn.query(`
    SELECT c.cow_id, SUM(gtd.trait_ebv) as sum_ebv
    FROM tb_genome_request gr
    JOIN tb_cow c ON gr.fk_cow_no = c.pk_cow_no
    JOIN tb_genome_trait_detail gtd ON gtd.cow_id = c.cow_id AND gtd.del_dt IS NULL
    WHERE gr.fk_farm_no = $1 AND gr.del_dt IS NULL AND c.del_dt IS NULL
      AND gr.chip_sire_name = '일치'
    GROUP BY c.cow_id
    HAVING COUNT(*) = 35
    ORDER BY sum_ebv DESC
  `, [farmNo]);

  const farmCows = farmCowsResult.rows;

  console.log('=== 농가 1번 개체별 선발지수 (가중 합계) ===\n');

  let total = 0;
  farmCows.forEach((c, i) => {
    const score = Number(c.sum_ebv);
    total += score;
    console.log(`${i+1}. ${c.cow_id}: ${score.toFixed(2)}`);
  });

  console.log('\n=== 계산 ===');
  console.log('개체 수:', farmCows.length);
  console.log('선발지수 총합:', total.toFixed(2));
  console.log('농가 평균 = 총합 / 개체수 =', total.toFixed(2), '/', farmCows.length, '=', (total / farmCows.length).toFixed(2));

  await conn.end();
}

main().catch(console.error);
