import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  if (!query?.type) {
    return [];
  }
  const datas = await dataSource.query(`
	select count(1) count,qdl.name from question q
left join question_difficulty_level qdl on q.difficulty_level = qdl.id
where q.type = ${query.type} ${
    user.baseRole === 2 ? "and q.creator = '" + user.userId + "'" : ''
  }
group by q.difficulty_level 

  `);
  const total = datas.reduce((prev, item) => {
    return prev + parseInt(item.count);
  }, 0);
  const formatDatas = datas.map((item) => {
    return {
      item: item.name,
      count: +item.count,
      percent: +item.count / total,
      total: total,
    };
  });
  return formatDatas;
}
