import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  if (!query?.exam) {
    return [];
  }
  const datas = await dataSource.query(`
	select
	sum(qfp.score) score,count(1) count,qt.name
from
	questions_for_paper qfp
left join exam e on
	e.exam_paper_id = qfp.exam_paper_id
	left join question q on q.id = qfp.question_id 
	left join question_type qt  on qt.id = q.type
where
	e.id = ${query.exam}
	group by q.type 

  `);
  const { totalCount, totalScore } = datas.reduce(
    (prev, item) => {
      prev.totalScore += +item.score;
      prev.totalCount += +item.count;
      return prev;
    },
    { totalCount: 0, totalScore: 0 },
  );
  const formatDatas = datas.map((item) => {
    return {
      ...item,
      score: +item.score,
      count: +item.count,
      totalCount,
      totalScore,
      scorePercent: +item.score / totalScore,
      countPercent: +item.count / totalCount,
    };
  });
  return formatDatas;
}
