package service

import (
	"fmt"
	"github.com/rs/zerolog"
	"go-humas-be/app/database/entity"
	requestPpidApproval "go-humas-be/app/module/ppid_data_approval_histories/request"
	ppidDataCategoriesRepository "go-humas-be/app/module/ppid_data_categories/repository"
	ppidDataFilesRepository "go-humas-be/app/module/ppid_data_files/repository"
	"go-humas-be/app/module/ppid_datas/mapper"
	"go-humas-be/app/module/ppid_datas/repository"
	"go-humas-be/app/module/ppid_datas/request"
	"go-humas-be/app/module/ppid_datas/response"
	userLevelsRepository "go-humas-be/app/module/user_levels/repository"
	userRoleLevelDetailsRepository "go-humas-be/app/module/user_role_level_details/repository"
	usersRepository "go-humas-be/app/module/users/repository"
	"go-humas-be/utils/paginator"
	utilSvc "go-humas-be/utils/service"
	"strconv"
	"strings"
	"time"
)

// PpidDatasService
type ppidDatasService struct {
	Repo                     repository.PpidDatasRepository
	PpidDataCategoriesRepo   ppidDataCategoriesRepository.PpidDataCategoriesRepository
	PpidDataFilesRepo        ppidDataFilesRepository.PpidDataFilesRepository
	UsersRepo                usersRepository.UsersRepository
	UserLevelsRepo           userLevelsRepository.UserLevelsRepository
	userRoleLevelDetailsRepo userRoleLevelDetailsRepository.UserRoleLevelDetailsRepository
	Log                      zerolog.Logger
}

// PpidDatasService define interface of IPpidDatasService
type PpidDatasService interface {
	All(req request.PpidDatasQueryRequest) (ppidDatas []*response.PpidDatasResponse, paging paginator.Pagination, err error)
	Show(id string) (ppidDatas *response.PpidDatasResponse, err error)
	Save(req request.PpidDatasCreateRequest, authToken string) (ppidDatas *entity.PpidDatas, err error)
	Update(id uint, req request.PpidDatasUpdateRequest) (err error)
	UpdateApprovalStatus(req requestPpidApproval.PpidDataApprovalHistoriesCreateRequest, authToken string) (err error)
	Delete(id uint) error
}

// NewPpidDatasService init PpidDatasService
func NewPpidDatasService(
	repo repository.PpidDatasRepository,
	ppidDataCategoriesRepo ppidDataCategoriesRepository.PpidDataCategoriesRepository,
	ppidDataFilesRepo ppidDataFilesRepository.PpidDataFilesRepository,
	usersRepo usersRepository.UsersRepository,
	userLevelsRepo userLevelsRepository.UserLevelsRepository,
	userRoleLevelDetailsRepo userRoleLevelDetailsRepository.UserRoleLevelDetailsRepository,
	log zerolog.Logger,
) PpidDatasService {

	return &ppidDatasService{
		Repo:                     repo,
		PpidDataCategoriesRepo:   ppidDataCategoriesRepo,
		PpidDataFilesRepo:        ppidDataFilesRepo,
		UsersRepo:                usersRepo,
		UserLevelsRepo:           userLevelsRepo,
		userRoleLevelDetailsRepo: userRoleLevelDetailsRepo,
		Log:                      log,
	}
}

// All implement interface of PpidDatasService
func (_i *ppidDatasService) All(req request.PpidDatasQueryRequest) (ppidDatass []*response.PpidDatasResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		ppidDatass = append(ppidDatass, mapper.PpidDatasResponseMapper(_i.Log, _i.PpidDataCategoriesRepo, _i.PpidDataFilesRepo, _i.UsersRepo, result))
	}

	return
}

func (_i *ppidDatasService) Show(id string) (ppidDatas *response.PpidDatasResponse, err error) {

	var result *entity.PpidDatas

	if utilSvc.IsNumeric(id) {
		idInt, _ := strconv.Atoi(id)
		result, err = _i.Repo.FindOne(uint(idInt))
		if err != nil {
			return nil, err
		}
	} else {
		result, err = _i.Repo.FindOneUsingSlug(id)
		if err != nil {
			return nil, err
		}
	}

	return mapper.PpidDatasResponseMapper(_i.Log, _i.PpidDataCategoriesRepo, _i.PpidDataFilesRepo, _i.UsersRepo, result), nil
}

func (_i *ppidDatasService) Save(req request.PpidDatasCreateRequest, authToken string) (ppidDatas *entity.PpidDatas, err error) {
	_i.Log.Info().Interface("data", req).Msg("")
	newReq := req.ToEntity()

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

	userLevels, err := _i.UserLevelsRepo.FindOne(uint(createdBy.UserLevelId))
	if err != nil {
		return nil, err
	}
	newReq.Group = userLevels.Group

	return _i.Repo.Create(newReq)
}

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

func (_i *ppidDatasService) UpdateApprovalStatus(req requestPpidApproval.PpidDataApprovalHistoriesCreateRequest, authToken string) (err error) {
	ppidData, err := _i.Repo.FindOne(req.PpidDataId)
	if err != nil {
		return err
	}

	if req.ApprovalStatusId == 1 {
		ppidData.NeedApprovalFromUserRole = nil
		ppidData.NeedApprovalFromUserLevel = nil
		ppidData.BackApprovalToUserRole = nil
		ppidData.BackApprovalToUserLevel = nil
	}

	approvalBy := utilSvc.GetUserInfo(_i.Log, _i.UsersRepo, authToken)
	if approvalBy != nil {
		findUserLevel, _ := _i.UserLevelsRepo.FindOne(uint(approvalBy.UserLevelId))
		findUserParentLevel, _ := _i.UserLevelsRepo.FindOne(uint(findUserLevel.ParentLevelId))
		if findUserLevel != nil {
			if findUserLevel.LevelNumber == 1 {
				isPublish := true
				publishLevel := 1
				timeNow := time.Now()
				ppidData.IsPublish = &isPublish
				ppidData.PublishLevel = &publishLevel
				ppidData.PublishedAt = &timeNow
				ppidData.NeedApprovalFromUserRole = nil
				ppidData.NeedApprovalFromUserLevel = nil
			} else if findUserLevel.LevelNumber == 2 {
				isPublish := true
				publishLevel := 2
				timeNow := time.Now()
				ppidData.IsPublish = &isPublish
				ppidData.PublishLevel = &publishLevel
				ppidData.PublishedAt = &timeNow

				needApprovalFromUserLevel := fmt.Sprintf("%s", findUserParentLevel.ID)
				ppidData.NeedApprovalFromUserLevel = &needApprovalFromUserLevel

				findUserRoles, _ := _i.userRoleLevelDetailsRepo.FindByUserLevels(findUserParentLevel.ID)
				var needApprovalFromUserRole []string
				for _, role := range findUserRoles {
					roleId := fmt.Sprintf("%s", role.UserRoleId)
					needApprovalFromUserRole = append(needApprovalFromUserRole, roleId)
				}
				needApprovalFromUserRoleStr := strings.Join(needApprovalFromUserRole, "/")
				ppidData.NeedApprovalFromUserRole = &needApprovalFromUserRoleStr
			}
		}
	}

	return _i.Repo.Update(req.PpidDataId, ppidData)
}

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

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