package auditlog

import (
	"encoding/json"
	"log"
)

func toJSONB(v any) any {
	if v == nil {
		return nil
	}
	b, err := json.Marshal(v)
	if err != nil {
		// JSON marshal hata olursa log’u bozmayalım
		log.Println("⚠️ auditlog json marshal error:", err)
		return nil
	}
	return b // pq jsonb için []byte kabul eder
}

func logWorker() {
	log.Println("🟢 auditlog worker STARTED")

	for entry := range logQueue {

		// ---------- DFUSR_ID ----------
		var dfusrID any
		if entry.DfUsrID > 0 {
			dfusrID = entry.DfUsrID
		} else {
			dfusrID = nil
		}

		// ---------- USERNAME ----------
		var username any
		if entry.Username != "" {
			username = entry.Username
		} else {
			username = nil
		}

		// ---------- ROLE CODE (SNAPSHOT) ----------
		roleCode := entry.RoleCode
		if roleCode == "" {
			roleCode = "public"
		}

		// ---------- TARGET ----------
		var targetDfUsrID any
		if entry.TargetDfUsrID > 0 {
			targetDfUsrID = entry.TargetDfUsrID
		} else {
			targetDfUsrID = nil
		}
		targetUsername := nullIfEmpty(entry.TargetUsername)

		log.Printf(
			"🧾 auditlog INSERT | actor_dfusr=%v actor_user=%v role=%s %s %s target=%v",
			dfusrID,
			username,
			roleCode,
			entry.ActionCategory,
			entry.ActionTarget,
			targetDfUsrID,
		)

		_, err := dbConn.Exec(`
			INSERT INTO mk_user_activity_log (
				log_id,
				dfusr_id,
				username,
				role_code,

				action_type,
				action_category,
				action_target,
				description,

				ip_address,
				user_agent,
				session_id,

				request_started_at,
				request_finished_at,
				duration_ms,
				http_status,

				is_success,
				error_message,

				-- ✅ NEW
				target_dfusr_id,
				target_username,
				change_before,
				change_after,

				created_at
			) VALUES (
				gen_random_uuid(),
				$1,$2,$3,
				$4,$5,$6,$7,
				$8,$9,$10,
				$11,$12,$13,$14,
				$15,$16,
				$17,$18,$19,$20,
				now()
			)
		`,
			dfusrID,
			username,
			roleCode,

			entry.ActionType,
			entry.ActionCategory,
			entry.ActionTarget,
			entry.Description,

			entry.IpAddress,
			entry.UserAgent,
			entry.SessionID,

			nullIfZeroTime(entry.RequestStartedAt),
			nullIfZeroTime(entry.RequestFinishedAt),
			nullIfZeroInt(entry.DurationMs),
			nullIfZeroInt(entry.HttpStatus),

			entry.IsSuccess,
			entry.ErrorMessage,

			// ✅ NEW
			targetDfUsrID,
			targetUsername,
			toJSONB(entry.ChangeBefore),
			toJSONB(entry.ChangeAfter),
		)

		if err != nil {
			log.Println("❌ auditlog insert error:", err)
		}
	}
}
