package menu

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

type MenuService struct {
	store *repository.Store
}

type MenuInput struct {
	ParentID       *uint
	Label          string
	Code           string
	Path           string
	Icon           string
	PermissionCode string
	Sort           int
	Visible        bool
}

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

func (s *MenuService) NavigationMenus(actor shared.Actor) ([]model.Menu, error) {
	return s.store.MenusForPermissions(actor.Permissions)
}

func (s *MenuService) ListSystemMenus() ([]model.Menu, error) {
	return s.store.ListMenus()
}

func (s *MenuService) CreateMenu(input MenuInput) (*model.Menu, error) {
	menu := menuFromInput(input)
	if err := s.store.CreateMenu(&menu); err != nil {
		return nil, err
	}
	return &menu, nil
}

func (s *MenuService) UpdateMenu(id uint, input MenuInput) (*model.Menu, error) {
	return s.store.UpdateMenu(id, menuFromInput(input))
}

func (s *MenuService) DeleteMenu(id uint) error {
	return s.store.DeleteMenu(id)
}

func (s *MenuService) UpdateMenuVisible(id uint, visible bool) (*model.Menu, error) {
	return s.store.UpdateMenuVisible(id, visible)
}

func (s *MenuService) SortMenus(items []repository.MenuSortItem) error {
	return s.store.SortMenus(items)
}

func menuFromInput(input MenuInput) model.Menu {
	return model.Menu{
		ParentID:       input.ParentID,
		Title:          input.Label,
		Code:           input.Code,
		Path:           input.Path,
		Icon:           input.Icon,
		PermissionCode: input.PermissionCode,
		Sort:           input.Sort,
		Visible:        input.Visible,
	}
}
