package workspaces

import (
	"context"
	"fmt"

	"apps/backend/internal/middleware"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListWorkspaceMembersLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListWorkspaceMembersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListWorkspaceMembersLogic {
	return &ListWorkspaceMembersLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}

func (l *ListWorkspaceMembersLogic) ListWorkspaceMembers(req *types.ListWorkspaceMembersReq) (*types.WorkspaceMemberListData, error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok || uid <= 0 {
		return nil, fmt.Errorf("unauthorized")
	}
	list, err := l.svcCtx.Growth.ListWorkspaceMembers(l.ctx, uid, req.Id)
	if err != nil {
		return nil, err
	}
	out := make([]types.WorkspaceMemberPublic, 0, len(list))
	for _, m := range list {
		email, name := "", fmt.Sprintf("uid %d", m.UID)
		if mem, err := l.svcCtx.Members.FindByUID(l.ctx, m.UID); err == nil && mem != nil {
			email = mem.Email
			if mem.DisplayName != "" {
				name = mem.DisplayName
			}
		}
		out = append(out, types.WorkspaceMemberPublic{
			Uid: m.UID, Email: email, DisplayName: name, Role: m.Role, JoinedAt: m.JoinedAt,
		})
	}
	return &types.WorkspaceMemberListData{List: out}, nil
}
