package repository

import (
	"fmt"
	"jaecoo-be/app/database"
	"jaecoo-be/app/database/entity"
	"jaecoo-be/app/module/user_roles/request"
	"jaecoo-be/utils/paginator"
	utilSvc "jaecoo-be/utils/service"
	"strings"

	"github.com/rs/zerolog"
)

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

// UserRolesRepository define interface of IUserRolesRepository
type UserRolesRepository interface {
	GetAll(req request.UserRolesQueryRequest) (userRoles []*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) (userRoles []*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.UserLevelId != nil {
		query = query.Where("user_level_id = ?", req.UserLevelId)
	}
	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(&userRoles).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) {
	userRolesMap, err := utilSvc.StructToMap(userRoles)
	if err != nil {
		return err
	}
	return _i.DB.DB.Model(&entity.UserRoles{}).
		Where(&entity.UserRoles{ID: id}).
		Updates(userRolesMap).Error
}

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