package repositories

import (
	"learnsteam/learsteam-quiz-api/internal/models"

	"gorm.io/gorm"
)

type examRepository struct {
	DB *gorm.DB
}

func NewExamRepository(db *gorm.DB) ExamRepository {
	return &examRepository{
		DB: db,
	}
}

type ExamRepository interface {
	List(string, int, int) (*[]models.Exam, error)
	Total(string) (int64, error)

	Find(string) (*models.Exam, error)
	Create(*models.Exam) (*models.Exam, error)
	Update(*models.Exam) (*models.Exam, error)
	Delete(string) error
}

func (r *examRepository) List(q string, page int, limit int) (*[]models.Exam, error) {
	var exams *[]models.Exam
	var err error
	offset := limit * (page - 1)
	if q != "" {
		err = r.DB.Offset(offset).Limit(limit).Order("created_at DESC").Where("subject LIKE ? OR program LIKE ? OR name LIKE ?", "%"+q+"%", "%"+q+"%", "%"+q+"%").Find(&exams).Error
	} else {
		err = r.DB.Offset(offset).Limit(limit).Order("created_at DESC").Find(&exams).Error
	}
	return exams, err
}

func (r *examRepository) Total(q string) (int64, error) {
	var total int64
	var err error
	if q != "" {
		err = r.DB.Model(&models.Exam{}).Where("subject LIKE ? OR program LIKE ? OR name LIKE ?", "%"+q+"%", "%"+q+"%", "%"+q+"%").Count(&total).Error
	} else {
		err = r.DB.Model(&models.Exam{}).Count(&total).Error
	}

	return total, err
}

func (r *examRepository) Find(id string) (*models.Exam, error) {
	var exam *models.Exam
	err := r.DB.Where("id = ?", id).First(&exam).Error
	return exam, err
}

func (r *examRepository) Create(exam *models.Exam) (*models.Exam, error) {
	err := r.DB.Create(&exam).Error
	return exam, err
}

func (r *examRepository) Update(exam *models.Exam) (*models.Exam, error) {
	var row *models.Exam
	if err := r.DB.Where("id=?", exam.ID).First(&row).Error; err != nil {
		return nil, err
	}

	err := r.DB.Model(&row).Select("*").Updates(&exam).Error
	return row, err
}

func (r *examRepository) Delete(id string) error {
	var exam *models.Exam
	if err := r.DB.Where("id=?", id).First(&exam).Error; err != nil {
		return err
	}
	err := r.DB.Delete(&exam).Error
	return err
}
