package db

import (
	"time"

	"server/internal/models"

	"gorm.io/gorm"
)

// ActiveExamInfo — phòng thi đang diễn ra cho sinh viên
type ActiveExamInfo struct {
	Room       models.ExamRoom
	Enrollment models.ExamRoomStudent
	Paper      *models.ExamPaper
}

// FindActiveExamForStudent trả về phòng thi nếu sinh viên đang trong khung giờ thi.
func FindActiveExamForStudent(db *gorm.DB, studentRkID int64) *ActiveExamInfo {
	if studentRkID <= 0 {
		return nil
	}
	now := time.Now()
	var enrollment models.ExamRoomStudent
	err := db.Table("exam_room_students AS ers").
		Select("ers.*").
		Joins("JOIN exam_rooms er ON er.id = ers.exam_room_id").
		Where("ers.student_rk_id = ? AND er.status = ? AND er.start_time <= ? AND er.end_time >= ?",
			studentRkID, models.ExamStatusReady, now, now).
		Order("er.start_time DESC").
		First(&enrollment).Error
	if err != nil {
		return nil
	}
	var room models.ExamRoom
	if err := db.First(&room, enrollment.ExamRoomID).Error; err != nil {
		return nil
	}
	info := &ActiveExamInfo{Room: room, Enrollment: enrollment}
	if enrollment.AssignedPaperID != nil {
		var paper models.ExamPaper
		if err := db.First(&paper, *enrollment.AssignedPaperID).Error; err == nil {
			info.Paper = &paper
		}
	}
	return info
}

// IsStudentInActiveExam kiểm tra nhanh sinh viên có đang thi không.
func IsStudentInActiveExam(db *gorm.DB, studentRkID int64) bool {
	return FindActiveExamForStudent(db, studentRkID) != nil
}
