package auth

import (
	"context"

	"github.com/google/uuid"
)

type contextKey string

const (
	userIDKey    contextKey = "user_id"
	tenantIDKey  contextKey = "tenant_id"
	ipKey        contextKey = "ip_address"
	userAgentKey contextKey = "user_agent"
	userRoleKey  contextKey = "user_role"
)

func ContextWithUserID(ctx context.Context, userID uuid.UUID) context.Context {
	return context.WithValue(ctx, userIDKey, userID)
}

func ContextWithTenantID(ctx context.Context, tenantID uuid.UUID) context.Context {
	return context.WithValue(ctx, tenantIDKey, tenantID)
}

func UserFromContext(ctx context.Context) (uuid.UUID, bool) {
	id, ok := ctx.Value(userIDKey).(uuid.UUID)
	return id, ok
}

func TenantFromContext(ctx context.Context) (uuid.UUID, bool) {
	id, ok := ctx.Value(tenantIDKey).(uuid.UUID)
	return id, ok
}

func ContextWithRequestInfo(ctx context.Context, ip, userAgent string) context.Context {
	ctx = context.WithValue(ctx, ipKey, ip)
	ctx = context.WithValue(ctx, userAgentKey, userAgent)
	return ctx
}

func IPFromContext(ctx context.Context) *string {
	if v, ok := ctx.Value(ipKey).(string); ok && v != "" {
		return &v
	}
	return nil
}

func UserAgentFromContext(ctx context.Context) *string {
	if v, ok := ctx.Value(userAgentKey).(string); ok && v != "" {
		return &v
	}
	return nil
}

func ContextWithUserRole(ctx context.Context, role string) context.Context {
	return context.WithValue(ctx, userRoleKey, role)
}

func UserRoleFromContext(ctx context.Context) string {
	role, _ := ctx.Value(userRoleKey).(string)
	return role
}
