package repository

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

type userRoleAccessesRepository struct {
	DB *database.Database
}

// UserRoleAccessesRepository define interface of IUserRoleAccessesRepository
type UserRoleAccessesRepository interface {
	GetAll(req request.UserRoleAccessesQueryRequest) (userRoleAccessess []*entity.UserRoleAccesses, paging paginator.Pagination, err error)
	FindOne(id uint) (userRoleAccesses *entity.UserRoleAccesses, err error)
	Create(userRoleAccesses *entity.UserRoleAccesses) (err error)
	Update(id uint, userRoleAccesses *entity.UserRoleAccesses) (err error)
	Delete(id uint) (err error)
}

func NewUserRoleAccessesRepository(db *database.Database) UserRoleAccessesRepository {
	return &userRoleAccessesRepository{
		DB: db,
	}
}

// implement interface of IUserRoleAccessesRepository
func (_i *userRoleAccessesRepository) GetAll(req request.UserRoleAccessesQueryRequest) (userRoleAccessess []*entity.UserRoleAccesses, paging paginator.Pagination, err error) {
	var count int64

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

	if req.UserRoleId != nil {
		query = query.Where("user_role_id = ?", req.UserRoleId)
	}
	if req.MenuId != nil {
		query = query.Where("menu_id = ?", req.MenuId)
	}
	query.Count(&count)

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

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

	paging = *req.Pagination

	return
}

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

	return userRoleAccesses, nil
}

func (_i *userRoleAccessesRepository) Create(userRoleAccesses *entity.UserRoleAccesses) (err error) {
	return _i.DB.DB.Create(userRoleAccesses).Error
}

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

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