"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExamsController = void 0;
const common_1 = require("@nestjs/common");
const swagger_1 = require("@nestjs/swagger");
const prisma_service_1 = require("../prisma/prisma.service");
const envelope_1 = require("../../common/envelope");
const roles_decorator_1 = require("../../common/decorators/roles.decorator");
const roles_1 = require("../../common/roles");
const class_validator_1 = require("class-validator");
const class_transformer_1 = require("class-transformer");
class CreateExamQuestionDto {
}
__decorate([
    (0, class_validator_1.IsString)(),
    __metadata("design:type", String)
], CreateExamQuestionDto.prototype, "text", void 0);
__decorate([
    (0, class_validator_1.IsOptional)(),
    (0, class_validator_1.IsString)(),
    __metadata("design:type", String)
], CreateExamQuestionDto.prototype, "type", void 0);
__decorate([
    (0, class_validator_1.IsOptional)(),
    (0, class_validator_1.IsArray)(),
    __metadata("design:type", Array)
], CreateExamQuestionDto.prototype, "options", void 0);
__decorate([
    (0, class_validator_1.IsOptional)(),
    (0, class_validator_1.IsString)(),
    __metadata("design:type", String)
], CreateExamQuestionDto.prototype, "correctAnswer", void 0);
__decorate([
    (0, class_validator_1.IsInt)(),
    (0, class_validator_1.Min)(1),
    __metadata("design:type", Number)
], CreateExamQuestionDto.prototype, "order", void 0);
class CreateExamDto {
}
__decorate([
    (0, class_validator_1.IsString)(),
    __metadata("design:type", String)
], CreateExamDto.prototype, "courseId", void 0);
__decorate([
    (0, class_validator_1.IsString)(),
    __metadata("design:type", String)
], CreateExamDto.prototype, "title", void 0);
__decorate([
    (0, class_validator_1.IsOptional)(),
    (0, class_validator_1.IsString)(),
    __metadata("design:type", String)
], CreateExamDto.prototype, "scheduledAt", void 0);
__decorate([
    (0, class_validator_1.IsOptional)(),
    (0, class_validator_1.IsInt)(),
    (0, class_validator_1.Min)(1),
    __metadata("design:type", Number)
], CreateExamDto.prototype, "durationMinutes", void 0);
__decorate([
    (0, class_validator_1.IsOptional)(),
    (0, class_validator_1.ValidateNested)({ each: true }),
    (0, class_transformer_1.Type)(() => CreateExamQuestionDto),
    __metadata("design:type", Array)
], CreateExamDto.prototype, "questions", void 0);
class SaveAnswerDto {
}
__decorate([
    (0, class_validator_1.IsString)(),
    __metadata("design:type", String)
], SaveAnswerDto.prototype, "questionId", void 0);
__decorate([
    (0, class_validator_1.IsString)(),
    __metadata("design:type", String)
], SaveAnswerDto.prototype, "answer", void 0);
let ExamsController = class ExamsController {
    constructor(prisma) {
        this.prisma = prisma;
    }
    async getExam(examId) {
        const exam = await this.prisma.exam.findUnique({ where: { id: examId }, include: { questions: { orderBy: { order: 'asc' } } } });
        return (0, envelope_1.ok)(exam);
    }
    async start(req, examId) {
        const userId = req.user.userId;
        const exam = await this.prisma.exam.findUnique({ where: { id: examId } });
        if (!exam)
            return (0, envelope_1.ok)({ error: 'Exam not found' });
        const enrollment = await this.prisma.enrollment.findFirst({ where: { userId, courseId: exam.courseId, status: 'ACTIVE' } });
        if (!enrollment)
            return (0, envelope_1.ok)({ error: 'Not enrolled or inactive' });
        const attempt = await this.prisma.examAttempt.create({ data: { examId, userId, status: 'IN_PROGRESS' } });
        return (0, envelope_1.ok)(attempt);
    }
    async saveAnswer(req, attemptId, dto) {
        const userId = req.user.userId;
        const attempt = await this.prisma.examAttempt.findFirst({ where: { id: attemptId, userId } });
        if (!attempt)
            return (0, envelope_1.ok)({ error: 'Attempt not found' });
        const ans = await this.prisma.examAttemptAnswer.upsert({
            where: { attemptId_questionId: { attemptId, questionId: dto.questionId } },
            create: { attemptId, questionId: dto.questionId, answer: dto.answer },
            update: { answer: dto.answer },
        });
        return (0, envelope_1.ok)(ans);
    }
    async submit(req, attemptId) {
        const userId = req.user.userId;
        const attempt = await this.prisma.examAttempt.findFirst({ where: { id: attemptId, userId }, include: { exam: { include: { questions: true } }, answers: true } });
        if (!attempt)
            return (0, envelope_1.ok)({ error: 'Attempt not found' });
        let correct = 0;
        const total = attempt.exam.questions.length || 1;
        const map = new Map(attempt.answers.map(a => [a.questionId, a.answer]));
        for (const q of attempt.exam.questions) {
            const a = map.get(q.id);
            if (q.correctAnswer && a != null && String(a).trim().toLowerCase() === String(q.correctAnswer).trim().toLowerCase())
                correct += 1;
        }
        const scorePercent = Math.round((correct / total) * 100);
        const updated = await this.prisma.examAttempt.update({ where: { id: attemptId }, data: { status: 'SUBMITTED', submittedAt: new Date(), scorePercent } });
        return (0, envelope_1.ok)(updated);
    }
    async create(dto) {
        const exam = await this.prisma.exam.create({
            data: {
                courseId: dto.courseId,
                title: dto.title,
                scheduledAt: dto.scheduledAt ? new Date(dto.scheduledAt) : undefined,
                durationMinutes: dto.durationMinutes ?? 60,
                questions: dto.questions ? { create: dto.questions.map(q => ({ text: q.text, type: (q.type ?? 'MCQ'), options: q.options ?? [], correctAnswer: q.correctAnswer, order: q.order })) } : undefined,
            },
            include: { questions: true },
        });
        return (0, envelope_1.ok)(exam);
    }
};
exports.ExamsController = ExamsController;
__decorate([
    (0, common_1.Get)('exams/:examId'),
    __param(0, (0, common_1.Param)('examId')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], ExamsController.prototype, "getExam", null);
__decorate([
    (0, common_1.Post)('exams/:examId/attempts'),
    __param(0, (0, common_1.Req)()),
    __param(1, (0, common_1.Param)('examId')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, String]),
    __metadata("design:returntype", Promise)
], ExamsController.prototype, "start", null);
__decorate([
    (0, common_1.Patch)('exams/attempts/:attemptId/answers'),
    __param(0, (0, common_1.Req)()),
    __param(1, (0, common_1.Param)('attemptId')),
    __param(2, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, String, SaveAnswerDto]),
    __metadata("design:returntype", Promise)
], ExamsController.prototype, "saveAnswer", null);
__decorate([
    (0, common_1.Post)('exams/attempts/:attemptId/submit'),
    __param(0, (0, common_1.Req)()),
    __param(1, (0, common_1.Param)('attemptId')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, String]),
    __metadata("design:returntype", Promise)
], ExamsController.prototype, "submit", null);
__decorate([
    (0, roles_decorator_1.Roles)(roles_1.UserRole.STAFF, roles_1.UserRole.ADMIN),
    (0, common_1.Post)('admin/exams'),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [CreateExamDto]),
    __metadata("design:returntype", Promise)
], ExamsController.prototype, "create", null);
exports.ExamsController = ExamsController = __decorate([
    (0, swagger_1.ApiTags)('Exams'),
    (0, swagger_1.ApiBearerAuth)(),
    (0, common_1.Controller)(),
    __metadata("design:paramtypes", [prisma_service_1.PrismaService])
], ExamsController);
//# sourceMappingURL=exams.controller.js.map