package repository

import (
	"fmt"
	"go-humas-be/app/database"
	"go-humas-be/app/database/entity"
	"go-humas-be/app/module/user_levels/request"
	"go-humas-be/utils/paginator"
	"strings"
)

type userLevelsRepository struct {
	DB *database.Database
}

// UserLevelsRepository define interface of IUserLevelsRepository
type UserLevelsRepository interface {
	GetAll(req request.UserLevelsQueryRequest) (userLevelss []*entity.UserLevels, paging paginator.Pagination, err error)
	FindOne(id uint) (userLevels *entity.UserLevels, err error)
	Create(userLevels *entity.UserLevels) (err error)
	Update(id uint, userLevels *entity.UserLevels) (err error)
	Delete(id uint) (err error)
}

func NewUserLevelsRepository(db *database.Database) UserLevelsRepository {
	return &userLevelsRepository{
		DB: db,
	}
}

// implement interface of IUserLevelsRepository
func (_i *userLevelsRepository) GetAll(req request.UserLevelsQueryRequest) (userLevelss []*entity.UserLevels, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.UserLevels{})
	query = query.Where("is_active = ?", true)

	if req.Name != nil && *req.Name != "" {
		name := strings.ToLower(*req.Name)
		query = query.Where("LOWER(name) LIKE ?", "%"+strings.ToLower(name)+"%")
	}
	if req.LevelNumber != nil {
		query = query.Where("level_number = ?", req.LevelNumber)
	}
	if req.ParentLevelId != nil {
		query = query.Where("parent_level_id = ?", req.ParentLevelId)
	}
	if req.ProvinceId != nil {
		query = query.Where("province_id = ?", req.ProvinceId)
	}
	query.Count(&count)

	if req.Pagination.SortBy != "" {
		direction := "ASC"
		if req.Pagination.Sort == "desc" {
			direction = "DESC"
		}
		query.Order(fmt.Sprintf("%s %s", req.Pagination.SortBy, direction))
	}

	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	err = query.Offset(req.Pagination.Offset).Limit(req.Pagination.Limit).Find(&userLevelss).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

func (_i *userLevelsRepository) FindOne(id uint) (userLevels *entity.UserLevels, err error) {
	if err := _i.DB.DB.First(&userLevels, id).Error; err != nil {
		return nil, err
	}

	return userLevels, nil
}

func (_i *userLevelsRepository) Create(userLevels *entity.UserLevels) (err error) {
	return _i.DB.DB.Create(userLevels).Error
}

func (_i *userLevelsRepository) Update(id uint, userLevels *entity.UserLevels) (err error) {
	return _i.DB.DB.Model(&entity.UserLevels{}).
		Where(&entity.UserLevels{ID: id}).
		Updates(userLevels).Error
}

func (_i *userLevelsRepository) Delete(id uint) error {
	return _i.DB.DB.Delete(&entity.UserLevels{}, id).Error
}
