package supportgroup

import (
	"context"
	"strings"
)

type Service struct {
	repo *Repository
}

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

func (s *Service) List(ctx context.Context) ([]GroupDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.List(ctx)
}

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

func (s *Service) Create(ctx context.Context, req CreateGroupRequest) (*GroupDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	req.Name = strings.TrimSpace(req.Name)
	if req.Name == "" {
		return nil, ErrInvalidGroup
	}
	return s.repo.Create(ctx, req)
}

func (s *Service) Update(ctx context.Context, id uint64, req UpdateGroupRequest) (*GroupDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	req.Name = strings.TrimSpace(req.Name)
	if id == 0 || req.Name == "" {
		return nil, ErrInvalidGroup
	}
	return s.repo.Update(ctx, id, req)
}

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

func (s *Service) AssignMembers(ctx context.Context, id uint64, req AssignMembersRequest) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	if id == 0 {
		return ErrInvalidGroup
	}
	return s.repo.AssignMembers(ctx, id, req.MemberIDs)
}

func (s *Service) ListSupportAdmins(ctx context.Context) ([]MemberDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.ListSupportAdmins(ctx)
}
