package service

import (
	"github.com/rs/zerolog"
	"web-qudo-be/app/database/entity"
	userLevelsRepository "web-qudo-be/app/module/user_levels/repository"
	userRoleAccessRepository "web-qudo-be/app/module/user_role_accesses/repository"
	userRoleLevelDetailsRepository "web-qudo-be/app/module/user_role_level_details/repository"
	"web-qudo-be/app/module/user_roles/mapper"
	"web-qudo-be/app/module/user_roles/repository"
	"web-qudo-be/app/module/user_roles/request"
	"web-qudo-be/app/module/user_roles/response"
	usersRepository "web-qudo-be/app/module/users/repository"
	"web-qudo-be/utils/paginator"
	utilSvc "web-qudo-be/utils/service"
)

// UserRolesService
type userRolesService struct {
	Repo                     repository.UserRolesRepository
	UsersRepo                usersRepository.UsersRepository
	UserLevelsRepo           userLevelsRepository.UserLevelsRepository
	UserRoleLevelDetailsRepo userRoleLevelDetailsRepository.UserRoleLevelDetailsRepository
	UserRoleAccessRepo       userRoleAccessRepository.UserRoleAccessesRepository
	Log                      zerolog.Logger
}

// UserRolesService define interface of IUserRolesService
type UserRolesService interface {
	All(req request.UserRolesQueryRequest) (userRoles []*response.UserRolesResponse, paging paginator.Pagination, err error)
	Show(id uint) (userRoles *response.UserRolesResponse, err error)
	Save(req request.UserRolesCreateRequest, authToken string) (err error)
	Update(id uint, req request.UserRolesUpdateRequest) (err error)
	Delete(id uint) error
}

// NewUserRolesService init UserRolesService
func NewUserRolesService(
	repo repository.UserRolesRepository,
	usersRepo usersRepository.UsersRepository,
	userLevelsRepo userLevelsRepository.UserLevelsRepository,
	userRoleLevelDetailsRepo userRoleLevelDetailsRepository.UserRoleLevelDetailsRepository,
	userRoleAccessRepo userRoleAccessRepository.UserRoleAccessesRepository,
	log zerolog.Logger,
) UserRolesService {

	return &userRolesService{
		Repo:                     repo,
		UsersRepo:                usersRepo,
		UserLevelsRepo:           userLevelsRepo,
		UserRoleLevelDetailsRepo: userRoleLevelDetailsRepo,
		UserRoleAccessRepo:       userRoleAccessRepo,
		Log:                      log,
	}
}

// All implement interface of UserRolesService
func (_i *userRolesService) All(req request.UserRolesQueryRequest) (userRoless []*response.UserRolesResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)

	if err != nil {
		return
	}

	for _, result := range results {
		userRoless = append(userRoless, mapper.UserRolesResponseMapper(result))
	}

	return
}

func (_i *userRolesService) Show(id uint) (userRoles *response.UserRolesResponse, err error) {
	result, err := _i.Repo.FindOne(id)
	if err != nil {
		return nil, err
	}

	return mapper.UserRolesResponseMapper(result), nil
}

func (_i *userRolesService) Save(req request.UserRolesCreateRequest, authToken string) (err error) {
	_i.Log.Info().Interface("data", req).Msg("")
	newReq := req.ToEntity()

	createdBy := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
	newReq.CreatedById = &createdBy.ID

	userRolesReturn, err := _i.Repo.Create(newReq)
	if err == nil {
		var userRoleAccessList []entity.UserRoleAccesses
		for _, item := range req.UserRoleAccess {
			userRoleAccess := entity.UserRoleAccesses{
				UserRoleId:        userRolesReturn.ID,
				MenuId:            item.MenuId,
				IsViewEnabled:     item.IsViewEnabled,
				IsInsertEnabled:   item.IsInsertEnabled,
				IsUpdateEnabled:   item.IsUpdateEnabled,
				IsDeleteEnabled:   item.IsDeleteEnabled,
				IsApprovalEnabled: item.IsApprovalEnabled,
				IsAdminEnabled:    item.IsAdminEnabled,
			}
			userRoleAccessList = append(userRoleAccessList, userRoleAccess)
		}
		err := _i.UserRoleAccessRepo.CreateAll(&userRoleAccessList)
		if err != nil {
			return err
		}

		var UserRoleLevelDetailList []entity.UserRoleLevelDetails
		isActive := true
		for _, id := range req.UserLevelIds {
			userRoleLevelDetail := entity.UserRoleLevelDetails{
				UserRoleId:  userRolesReturn.ID,
				UserLevelId: id,
				IsActive:    &isActive,
			}
			UserRoleLevelDetailList = append(UserRoleLevelDetailList, userRoleLevelDetail)
		}
		err = _i.UserRoleLevelDetailsRepo.CreateAll(&UserRoleLevelDetailList)
		if err != nil {
			return err
		}
	}

	return err
}

func (_i *userRolesService) Update(id uint, req request.UserRolesUpdateRequest) (err error) {
	_i.Log.Info().Interface("data", req).Msg("")
	return _i.Repo.Update(id, req.ToEntity())
}

func (_i *userRolesService) Delete(id uint) (err error) {
	result, err := _i.Repo.FindOne(id)
	if err != nil {
		return err
	}

	isActive := false
	result.IsActive = &isActive
	return _i.Repo.Update(id, result)
}
