package auth

import (
	"context"

	memberDomain "apps/backend/internal/module/member/domain"
	radarDomain "apps/backend/internal/module/radar/domain"
	"apps/backend/internal/svc"
)

// ensureOnboarding fills completed for legacy members with an empty status who
// already have a brand, product, or demand watch. An explicit pending stays
// pending so a reset (for retest) is not immediately overwritten.
func ensureOnboarding(ctx context.Context, svcCtx *svc.ServiceContext, m *memberDomain.Member) *memberDomain.Member {
	if m == nil || m.OnboardingStatus != "" {
		return m
	}
	if !hasExistingSetup(ctx, svcCtx, m.UID) {
		return m
	}
	status := memberDomain.OnboardingCompleted
	updated, err := svcCtx.Auth.UpdateUserInfo(ctx, m.UID, &memberDomain.UpdateUserInfoPatch{
		OnboardingStatus: &status,
	})
	if err != nil || updated == nil {
		return m
	}
	return updated
}

func hasExistingSetup(ctx context.Context, svcCtx *svc.ServiceContext, uid int64) bool {
	if svcCtx == nil || uid <= 0 {
		return false
	}
	if svcCtx.Scout != nil {
		if brands, err := svcCtx.Scout.ListBrands(ctx, uid); err == nil && len(brands) > 0 {
			return true
		}
		if products, err := svcCtx.Scout.ListAllProducts(ctx, uid); err == nil && len(products) > 0 {
			return true
		}
	}
	if svcCtx.Radar != nil {
		if _, total, err := svcCtx.Radar.ListWatches(ctx, uid, radarDomain.WatchListFilter{Page: 1, PageSize: 1}); err == nil && total > 0 {
			return true
		}
	}
	return false
}
