package repository

import (
	"fmt"
	"github.com/rs/zerolog"
	"go-humas-be/app/database"
	"go-humas-be/app/database/entity"
	"go-humas-be/app/module/user_roles/request"
	"go-humas-be/utils/paginator"
	"strings"
)

type userRolesRepository struct {
	DB  *database.Database
	Log zerolog.Logger
}

// UserRolesRepository define interface of IUserRolesRepository
type UserRolesRepository interface {
	GetAll(req request.UserRolesQueryRequest) (userRoless []*entity.UserRoles, paging paginator.Pagination, err error)
	FindOne(id uint) (userRoles *entity.UserRoles, err error)
	Create(userRoles *entity.UserRoles) (userRolesReturn *entity.UserRoles, err error)
	Update(id uint, userRoles *entity.UserRoles) (err error)
	Delete(id uint) (err error)
}

func NewUserRolesRepository(db *database.Database, log zerolog.Logger) UserRolesRepository {
	return &userRolesRepository{
		DB:  db,
		Log: log,
	}
}

// implement interface of IUserRolesRepository
func (_i *userRolesRepository) GetAll(req request.UserRolesQueryRequest) (userRoless []*entity.UserRoles, paging paginator.Pagination, err error) {
	_i.Log.Info().Interface("data", req).Msg("")

	var count int64

	query := _i.DB.DB.Model(&entity.UserRoles{})
	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.Code != nil {
		query = query.Where("code = ?", req.Code)
	}
	if req.LevelNumber != nil {
		query = query.Where("level_number = ?", req.LevelNumber)
	}
	if req.StatusId != nil {
		query = query.Where("status_id = ?", req.StatusId)
	}
	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(&userRoless).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

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

	return userRoles, nil
}

func (_i *userRolesRepository) Create(userRoles *entity.UserRoles) (userRolesReturn *entity.UserRoles, err error) {
	result := _i.DB.DB.Create(userRoles)
	return userRoles, result.Error
}

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

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