package appregistry

import (
	"database/sql"

	"hyapp-admin-server/internal/middleware"
	"hyapp-admin-server/internal/repository"
	"hyapp-admin-server/internal/response"

	"github.com/gin-gonic/gin"
)

type Handler struct {
	service *Service
	store   *repository.Store
}

func New(userDB *sql.DB, store *repository.Store) *Handler {
	return &Handler{service: NewService(userDB), store: store}
}

func (h *Handler) ListApps(c *gin.Context) {
	items, err := h.service.ListApps(c.Request.Context())
	if err != nil {
		response.ServerError(c, "获取 App 列表失败")
		return
	}
	response.OK(c, gin.H{"items": items, "total": len(items)})
}

func (h *Handler) ListVisibleApps(c *gin.Context) {
	access, err := h.store.AppAccessForUser(middleware.CurrentUserID(c))
	if err != nil {
		response.ServerError(c, "获取 App 权限失败")
		return
	}
	items, err := h.service.ListApps(c.Request.Context())
	if err != nil {
		response.ServerError(c, "获取 App 列表失败")
		return
	}
	visible := make([]App, 0, len(items))
	for _, item := range items {
		if access.Allows(item.AppCode) {
			visible = append(visible, item)
		}
	}
	response.OK(c, gin.H{"items": visible, "total": len(visible), "mode": access.Mode})
}
