package auth

import (
	"context"

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

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

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

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

func (l *MeLogic) Me() (resp *types.MemberPublic, err error) {
	m, ok := middleware.MemberFrom(l.ctx)
	if !ok || m == nil {
		uid, _ := middleware.UIDFrom(l.ctx)
		var err error
		m, err = l.svcCtx.Auth.Me(l.ctx, uid)
		if err != nil {
			return nil, err
		}
	}
	m = ensureOnboarding(l.ctx, l.svcCtx, m)
	ids, _ := l.svcCtx.Auth.ListIdentities(l.ctx, m.UID)
	return types.MemberFromModelWithIdentities(m, ids), nil
}
