package db

import (
	"time"

	"server/internal/models"

	"gorm.io/gorm"
)

// ExamDisplayStatus trạng thái hiển thị (tính từ DB status + thời gian).
func ExamDisplayStatus(room models.ExamRoom, now time.Time) string {
	switch room.Status {
	case models.ExamStatusCancelled:
		return models.ExamStatusCancelled
	case models.ExamStatusEnded:
		return models.ExamStatusEnded
	case models.ExamStatusDraft:
		return models.ExamStatusDraft
	case models.ExamStatusReady:
		if now.After(room.EndTime) {
			return models.ExamStatusEnded
		}
		if !now.Before(room.StartTime) {
			return "active"
		}
		return models.ExamStatusReady
	default:
		return models.ExamStatusDraft
	}
}

func ExamRoomEditable(room models.ExamRoom) bool {
	return room.Status == models.ExamStatusDraft
}

// ExamRoomPrepEditable — chỉnh gói đề, sinh viên trước khi thi bắt đầu.
func ExamRoomPrepEditable(room models.ExamRoom, now time.Time) bool {
	if room.Status == models.ExamStatusDraft {
		return true
	}
	return room.Status == models.ExamStatusReady && now.Before(room.StartTime)
}

func ExamRoomCanUnpublish(room models.ExamRoom, now time.Time) bool {
	return room.Status == models.ExamStatusReady && now.Before(room.StartTime)
}

func ExamRoomIsLive(room models.ExamRoom, now time.Time) bool {
	return ExamDisplayStatus(room, now) == "active"
}

func ExamRoomCanCancel(room models.ExamRoom, now time.Time) bool {
	return ExamRoomIsLive(room, now)
}

// ProcessExamRoomLifecycle đánh dấu phòng ready đã quá giờ kết thúc.
func ProcessExamRoomLifecycle(db *gorm.DB) {
	now := time.Now()
	_ = db.Model(&models.ExamRoom{}).
		Where("status = ? AND end_time < ?", models.ExamStatusReady, now).
		Update("status", models.ExamStatusEnded).Error
}
