package team

import (
	"strings"

	"hyapp-admin-server/internal/model"
	"hyapp-admin-server/internal/modules/shared"
	"hyapp-admin-server/internal/repository"
)

type Service struct {
	store *repository.Store
}

type Input struct {
	Name        string
	ParentID    *uint
	Description string
	Sort        int
}

func NewService(store *repository.Store) *Service {
	return &Service{store: store}
}

func (s *Service) ListTeams(keyword string) ([]model.Team, error) {
	return s.store.ListTeams(keyword)
}

func (s *Service) CreateTeam(input Input) (*model.Team, error) {
	team := model.Team{
		ParentID:    input.ParentID,
		Name:        strings.TrimSpace(input.Name),
		Description: strings.TrimSpace(input.Description),
		Sort:        input.Sort,
	}
	if err := s.store.CreateTeam(&team); err != nil {
		return nil, err
	}
	return s.store.GetTeam(team.ID)
}

func (s *Service) UpdateTeam(id uint, input Input) (*model.Team, error) {
	return s.store.UpdateTeam(id, model.Team{
		ParentID:    input.ParentID,
		Name:        strings.TrimSpace(input.Name),
		Description: strings.TrimSpace(input.Description),
		Sort:        input.Sort,
	})
}

func (s *Service) ListTeamUsers(actor shared.Actor, teamID uint, options repository.ListOptions) ([]model.User, int64, error) {
	if _, err := s.store.GetTeam(teamID); err != nil {
		return nil, 0, err
	}
	access, err := s.store.DataAccessForUser(actor.UserID)
	if err != nil {
		return nil, 0, err
	}
	teamIDs, err := s.store.TeamAndChildIDs(teamID)
	if err != nil {
		return nil, 0, err
	}
	options.TeamIDs = teamIDs
	return s.store.ListUsersWithAccess(options, access)
}
