package member

import (
	"context"

	"haixun-backend/internal/library/authctx"
	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/model/member/domain/entity"
	placementusecase "haixun-backend/internal/model/placement/usecase"
	"haixun-backend/internal/types"
)

func actorFrom(ctx context.Context) (tenantID, uid string, err error) {
	actor, ok := authctx.ActorFromContext(ctx)
	if !ok {
		return "", "", app.For(code.Auth).AuthUnauthorized("missing actor")
	}
	return actor.TenantID, actor.UID, nil
}

func toPlacementSettingsData(settings *placementusecase.Settings) types.MemberPlacementSettingsData {
	if settings == nil {
		return types.MemberPlacementSettingsData{}
	}
	return types.MemberPlacementSettingsData{
		WebSearchProvider:     settings.WebSearchProvider,
		BraveAPIKey:           settings.BraveAPIKey,
		BraveAPIKeyConfigured: settings.BraveAPIKeyConfigured,
		ExaAPIKey:             settings.ExaAPIKey,
		ExaAPIKeyConfigured:   settings.ExaAPIKeyConfigured,
		BraveCountry:          settings.BraveCountry,
		BraveSearchLang:       settings.BraveSearchLang,
		ExaUserLocation:       settings.ExaUserLocation,
		ExpandStrategy:        settings.ExpandStrategy,
	}
}

func toMemberMeData(member *entity.Member) *types.MemberMeData {
	if member == nil {
		return nil
	}
	return &types.MemberMeData{
		TenantID:              member.TenantID,
		UID:                   member.UID,
		Email:                 member.Email,
		DisplayName:           member.DisplayName,
		Avatar:                member.Avatar,
		Phone:                 member.Phone,
		Language:              member.Language,
		Currency:              member.Currency,
		Status:                string(member.Status),
		Origin:                string(member.Origin),
		Roles:                 member.Roles,
		BusinessEmail:         member.BusinessEmail,
		BusinessEmailVerified: member.BusinessEmailVerified,
		BusinessPhone:         member.BusinessPhone,
		BusinessPhoneVerified: member.BusinessPhoneVerified,
		CreateAt:              member.CreateAt,
		UpdateAt:              member.UpdateAt,
	}
}
