package repositories

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

	"gorm.io/gorm"
)

type quizRepository struct {
	DB *gorm.DB
}

func NewQuizRepository(db *gorm.DB) QuizRepository {
	return &quizRepository{
		DB: db,
	}
}

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

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

func (r *quizRepository) List(program_id string, page int, limit int) (*[]models.Quiz, error) {
	var quizzes *[]models.Quiz
	var err error
	offset := limit * (page - 1)
	if program_id != "" {
		fmt.Println("program_id", program_id)
		err = r.DB.Offset(offset).Limit(limit).Order("sequence ASC").Where("program_id = ?", program_id).Find(&quizzes).Error
	} else {
		fmt.Println("program_id", "none")
		err = r.DB.Offset(offset).Limit(limit).Find(&quizzes).Error
	}
	return quizzes, err
}

func (r *quizRepository) Total(program_id string) (int64, error) {
	var total int64
	var err error
	if program_id != "" {
		err = r.DB.Model(&models.Quiz{}).Where("program_id = ?", program_id).Count(&total).Error
	} else {
		err = r.DB.Model(&models.Quiz{}).Count(&total).Error
	}

	return total, err
}

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

func (r *quizRepository) Create(quiz *models.Quiz) (*models.Quiz, error) {
	err := r.DB.Create(&quiz).Error
	return quiz, err
}

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

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

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