import { z } from 'zod';

// {
//     "type": "string",
//     "topic_id": 0,
//     "complexity_code": 0,
//     "status": "string",
//     "title": "string",
//     "description": "string",
//     "answer_explanation": "string",
//     "source": "string",
//     "tags": {
//       "idList": [
//         0
//       ]
//     },
//     "options": [
//       {
//         "text": "string",
//         "isCorrect": true
//       }
//     ]
// }

const Option = z.object({
    text: z.string(),
    isCorrect: z.boolean(),
});

const BaseQuestionShape = z.object({
    topic_id: z.number(),
    complexity_code: z.number(),
    status: z.enum(["PUBLISHED", "DRAFT"]),
    title: z.string(),
    description: z.string().optional(),
    answer_explanation: z.string(),
    source: z.enum(["BULK UPLOAD", "MANUAL ENTRY"]),
});

const SpecificTypeQuestionShape = z.discriminatedUnion('type', [
    // type : "MCQ"
    z.object({
        type: z.literal("MCQ"),
        answer: z.array(z.string()).length(1, "Needs have ONLY one answer in 'MCQ' type questions."),
        options: z.array(Option).min(2, "Options can not be less than two!").max(6, "Options are more than six!"),
    }),
    // type : "MRQ"
    z.object({
        type: z.literal("MRQ"),
        answer: z.array(z.string()).min(2, "Can not have less than two answer in 'MRQ' type questions")
            .max(6, "Can not have more than six answer in 'MRQ' type questions"),
        options: z.array(Option).min(2, "Options can not be less than two!").max(6, "Options are more than six!"),
    }),
    // type: "TNF"
    z.object({
        type: z.literal("TNF"),
        answer: z.array(z.string()).length(1, "Needs have ONLY one answer in 'TNF' type questions."),
        options: z.array(Option).length(2, "True and False Questions can only have two options!")
    })
])
.and(BaseQuestionShape)
.superRefine((val,ctx) => {
    const {answer, options, type} = val;
    // console.log("------------>", answer, options);
    if(type !== "TNF") {
        for(let item of answer) {
            if(item > options.length) {   // dev logic, change it to proper logic
                ctx.addIssue({
                    code: z.ZodIssueCode.too_big,
                    maximum: options.length,
                    type: "number",
                    inclusive: true,
                    message: "An item in answer array is greater than number of options available.",
                    path: ["answer"]
                });
            }
        }
    } else {
        if(!(answer[0] === "true" || answer[0] === "false")) {
            ctx.addIssue({
                code: z.ZodIssueCode.custom,
                message: "The answer for TNF question is something other than true or false.",
                path: ["answer"]
            });
        }
    }
})
.transform(input => {
    const obj = input;
    delete obj.answer;
    return obj;
});

export const BulkQuestionObj = z.array(SpecificTypeQuestionShape);