package repositories

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

	"gorm.io/gorm"
)

type userRepository struct {
	DB *gorm.DB
}

func NewUserRepository(db *gorm.DB) UserRepository {
	return &userRepository{
		DB: db,
	}
}

type UserRepository interface {
	List(string, int, int) (*[]models.User, error)
	Total(string) (int64, error)
	Find(string) (*models.User, error)
	FindByUsername(string) (*models.User, error)
	Create(*models.User) (*models.User, error)
	Update(*models.User) (*models.User, error)
	Delete(string) error
}

func (r *userRepository) List(q string, page int, limit int) (*[]models.User, error) {
	var users *[]models.User
	var err error
	offset := limit * (page - 1)
	fmt.Println("q", q)
	if q != "" {
		err = r.DB.Offset(offset).Limit(limit).Order("name ASC").Where("name LIKE ? OR username LIKE ?", "%"+q+"%", "%"+q+"%").Find(&users).Error
	} else {
		fmt.Println(" query")
		err = r.DB.Offset(offset).Limit(limit).Order("created_at DESC").Find(&users).Error
	}
	return users, err
}

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

	return total, err
}

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

func (r *userRepository) FindByUsername(username string) (*models.User, error) {
	var user *models.User
	err := r.DB.Where("username = ?", username).First(&user).Error
	return user, err
}

func (r *userRepository) Create(user *models.User) (*models.User, error) {
	err := r.DB.Create(&user).Error
	return user, err
}

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

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

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