package adminmgr

import "errors"

var ErrDependencyUnavailable = errors.New("dependency unavailable")

type Service struct {
	repo *Repository
}

func NewService(repo *Repository) *Service {
	return &Service{repo: repo}
}

func (s *Service) List(page, pageSize int) (*PaginatedResult, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 20
	}
	return s.repo.List(page, pageSize)
}

func (s *Service) FindByID(id uint64) (*AdminUserDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.FindByID(id)
}

func (s *Service) Create(req CreateAdminRequest) (*AdminUserDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if len(req.Password) < 6 {
		return nil, errors.New("password too short")
	}
	return s.repo.Create(req)
}

func (s *Service) Update(id uint64, req UpdateAdminRequest) (*AdminUserDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.Update(id, req)
}

func (s *Service) Delete(id uint64, currentAdminID uint64) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.Delete(id, currentAdminID)
}

func (s *Service) AssignRoles(adminID uint64, req AssignRolesRequest) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.AssignRoles(adminID, req.RoleIDs)
}

func (s *Service) ChangePassword(id uint64, req ChangePasswordRequest) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	if len(req.NewPassword) < 6 {
		return errors.New("new password too short")
	}
	return s.repo.ChangePassword(id, req.OldPassword, req.NewPassword)
}
