package api

import (
	"copter-train/db/repo"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

// 生成考核试题
// /exeam/generate/:scope
type GenerateExeamReq struct {
	ChoiceNum int `json:"choiceNum"` // 选择题生成多少道
	JudgeNum  int `json:"judgeNum"`  // 判断题生成多少道
}

func GenerateExeam(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	db := c.Param("scope")
	var form GenerateExeamReq
	err := c.ShouldBindJSON(&form)
	if err != nil {
		return nil, err
	}
	// 查询所有试题
	ctx := apictx.CreateRepoCtx().Ctx
	mongoClient := apictx.CreateRepoCtx().Client
	col := mongoClient.GetDbCollection(db, repo.CollectionTest)
	pipeline := mongo.Pipeline{
		{
			{Key: "$facet", Value: bson.M{
				"choiceQuestions": bson.A{
					bson.M{"$match": bson.M{"type": "选择"}},
					bson.M{"$sample": bson.M{"size": form.ChoiceNum}},
				},
				"judgeQuestions": bson.A{
					bson.M{"$match": bson.M{"type": "判断"}},
					bson.M{"$sample": bson.M{"size": form.JudgeNum}},
				},
			}},
		},
	}
	cursor, err := col.Aggregate(ctx, pipeline)
	if err != nil {
		return nil, err
	}
	var result []bson.M
	if err = cursor.All(ctx, &result); err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)

	if len(result) == 0 {
		return map[string]interface{}{
			"choiceQuestions": []bson.M{},
			"judgeQuestions":  []bson.M{},
		}, nil
	}
	return result[0], nil
}
