package workspaces

import (
	"context"
	"fmt"
	"strings"

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

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

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

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

func (l *AddWorkspaceMemberLogic) AddWorkspaceMember(req *types.AddWorkspaceMemberReq) (*types.WorkspaceMemberPublic, error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok || uid <= 0 {
		return nil, fmt.Errorf("unauthorized")
	}
	memberUID := req.MemberUid
	email, name := "", ""
	if memberUID <= 0 && strings.TrimSpace(req.Email) != "" {
		mem, err := l.svcCtx.Members.FindByEmail(l.ctx, strings.TrimSpace(req.Email))
		if err != nil || mem == nil {
			return nil, fmt.Errorf("member not found by email")
		}
		memberUID = mem.UID
		email = mem.Email
		name = mem.DisplayName
	} else if memberUID > 0 {
		if mem, err := l.svcCtx.Members.FindByUID(l.ctx, memberUID); err == nil && mem != nil {
			email = mem.Email
			name = mem.DisplayName
		}
	}
	m, err := l.svcCtx.Growth.AddWorkspaceMember(l.ctx, uid, memberUID, req.WorkspaceId, req.Role)
	if err != nil {
		return nil, err
	}
	if name == "" {
		name = fmt.Sprintf("uid %d", m.UID)
	}
	return &types.WorkspaceMemberPublic{
		Uid: m.UID, Email: email, DisplayName: name, Role: m.Role, JoinedAt: m.JoinedAt,
	}, nil
}
