package permission

import (
	"context"

	"haixun-backend/internal/library/authctx"
	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

type GetMePermissionsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetMePermissionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMePermissionsLogic {
	return &GetMePermissionsLogic{ctx: ctx, svcCtx: svcCtx}
}

func (l *GetMePermissionsLogic) GetMePermissions(req *types.MePermissionsQuery) (*types.MePermissionsData, error) {
	actor, ok := authctx.ActorFromContext(l.ctx)
	if !ok {
		return nil, app.For(code.Auth).AuthUnauthorized("missing actor")
	}
	member, err := l.svcCtx.Member.GetByUID(l.ctx, actor.TenantID, actor.UID)
	if err != nil {
		return nil, err
	}
	perms, err := l.svcCtx.Permission.Me(l.ctx, member, req.IncludeTree)
	if err != nil {
		return nil, err
	}
	return &types.MePermissionsData{
		UID:         perms.UID,
		TenantID:    perms.TenantID,
		Roles:       perms.Roles,
		Permissions: perms.Permissions,
		Tree:        toPermissionNodes(perms.Tree),
	}, nil
}
