package provision

import (
	"crypto/sha256"
	"encoding/hex"
	"strings"

	"sub2api-cn-relay-manager/internal/access"
	"sub2api-cn-relay-manager/internal/host/sub2api"
)

func BuildAccessClosureDetails(accessReq AccessRequest, gateway sub2api.GatewayAccessResult) map[string]any {
	details := map[string]any{
		"subscription_users": subscriptionUserIDs(accessReq.Subscriptions),
		"subscription_days":  subscriptionDurationDays(accessReq.Subscriptions),
		"status_code":        gateway.StatusCode,
		"ok":                 gateway.OK,
		"has_expected_model": gateway.HasExpectedModel,
		"models":             gateway.Models,
		"completion_ok":      gateway.CompletionOK,
		"completion_status":  gateway.CompletionStatus,
		"completion_type":    gateway.CompletionType,
		"completion_preview": gateway.CompletionBody,
	}

	requestedProbeAPIKey := strings.TrimSpace(accessReq.ProbeAPIKey)
	if requestedProbeAPIKey != "" {
		details["requested_probe_api_key"] = requestedProbeAPIKey
	}

	effectiveProbeKeySource := strings.TrimSpace(gateway.EffectiveProbeKeySource)
	if effectiveProbeKeySource != "" {
		details["effective_probe_key_source"] = effectiveProbeKeySource
	}

	effectiveProbeAPIKey := strings.TrimSpace(gateway.EffectiveProbeAPIKey)
	if effectiveProbeAPIKey != "" {
		details["effective_probe_key_fingerprint"] = fingerprintSecret(effectiveProbeAPIKey)
	}

	if strings.TrimSpace(accessReq.Mode) == AccessModeSelfService && requestedProbeAPIKey != "" {
		details["probe_api_key"] = requestedProbeAPIKey
		if effectiveProbeKeySource == "" {
			details["effective_probe_key_source"] = access.ProbeKeySourceRequestedProbeAPIKey
		}
		if effectiveProbeAPIKey == "" {
			details["effective_probe_key_fingerprint"] = fingerprintSecret(requestedProbeAPIKey)
		}
	}

	return details
}

func fingerprintSecret(value string) string {
	trimmed := strings.TrimSpace(value)
	if trimmed == "" {
		return ""
	}
	sum := sha256.Sum256([]byte(trimmed))
	return "sha256:" + hex.EncodeToString(sum[:])
}
