package appctx

import (
	"context"
	"strings"
)

const (
	DefaultAppCode = "lalu"
	HeaderAppCode  = "X-App-Code"
)

type contextKey struct{}
type externalScopeKey struct{}

// ExternalScope contains only server-derived portal authority. Business modules may
// consume it to narrow owner-service calls, but must never construct it from request JSON.
type ExternalScope struct {
	AccountID       uint64
	LinkedAppUserID int64
	IdentityType    string
	RegionID        int64
	OwnerUserIDs    []int64
}

func Normalize(value string) string {
	value = strings.ToLower(strings.TrimSpace(value))
	if value == "" {
		return DefaultAppCode
	}
	return value
}

func WithContext(ctx context.Context, value string) context.Context {
	return context.WithValue(ctx, contextKey{}, Normalize(value))
}

func FromContext(ctx context.Context) string {
	if ctx == nil {
		return DefaultAppCode
	}
	value, _ := ctx.Value(contextKey{}).(string)
	return Normalize(value)
}

func WithExternalScope(ctx context.Context, scope ExternalScope) context.Context {
	scope.OwnerUserIDs = append([]int64(nil), scope.OwnerUserIDs...)
	return context.WithValue(ctx, externalScopeKey{}, scope)
}

func ExternalScopeFromContext(ctx context.Context) (ExternalScope, bool) {
	if ctx == nil {
		return ExternalScope{}, false
	}
	scope, ok := ctx.Value(externalScopeKey{}).(ExternalScope)
	if !ok {
		return ExternalScope{}, false
	}
	scope.OwnerUserIDs = append([]int64(nil), scope.OwnerUserIDs...)
	return scope, true
}
