package member

import (
	"context"

	"haixun-backend/internal/library/authctx"
	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	memberusecase "haixun-backend/internal/model/member/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

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

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

func (l *UpdateMemberMeLogic) UpdateMemberMe(req *types.UpdateMemberMeReq) (*types.MemberMeData, error) {
	actor, ok := authctx.ActorFromContext(l.ctx)
	if !ok {
		return nil, app.For(code.Auth).AuthUnauthorized("missing actor")
	}
	member, err := l.svcCtx.Member.UpdateProfile(l.ctx, memberusecase.UpdateProfileRequest{
		TenantID:    actor.TenantID,
		UID:         actor.UID,
		DisplayName: optionalString(req.DisplayName),
		Avatar:      optionalString(req.Avatar),
		Language:    optionalString(req.Language),
		Currency:    optionalString(req.Currency),
		Phone:       optionalString(req.Phone),
	})
	if err != nil {
		return nil, err
	}
	return toMemberMeData(member), nil
}

func optionalString(value string) *string {
	if value == "" {
		return nil
	}
	return &value
}
