package adminmgr

import (
	"context"
	"errors"
	"unicode"
)

var (
	ErrDependencyUnavailable = errors.New("dependency unavailable")
	ErrWeakPassword          = errors.New("weak password")
)

type Service struct {
	repo *Repository
}

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

func (s *Service) List(ctx context.Context, 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(ctx, page, pageSize)
}

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

func (s *Service) Create(ctx context.Context, req CreateAdminRequest) (*AdminUserDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if !passwordStrongEnough(req.Password) {
		return nil, ErrWeakPassword
	}
	return s.repo.Create(ctx, req)
}

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

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

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

func (s *Service) ChangeOwnPassword(ctx context.Context, adminID uint64, req ChangePasswordRequest) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	if !passwordStrongEnough(req.NewPassword) {
		return ErrWeakPassword
	}
	return s.repo.ChangeOwnPassword(ctx, adminID, req.OldPassword, req.NewPassword)
}

func (s *Service) ResetPassword(ctx context.Context, id uint64, req ResetPasswordRequest) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	if !passwordStrongEnough(req.NewPassword) {
		return ErrWeakPassword
	}
	return s.repo.ResetPassword(ctx, id, req.NewPassword)
}

func passwordStrongEnough(value string) bool {
	if len([]rune(value)) < 8 {
		return false
	}
	hasLetter := false
	hasDigit := false
	for _, r := range value {
		if unicode.IsLetter(r) {
			hasLetter = true
		}
		if unicode.IsDigit(r) {
			hasDigit = true
		}
	}
	return hasLetter && hasDigit
}
