package services

import (
	"encoding/json"
	"log"

	"github.com/google/uuid"
	"github.com/tapper/backend/database"
	"github.com/tapper/backend/models"
)

func LogAudit(actorID uuid.UUID, action, targetType string, targetID *uuid.UUID, details interface{}, ipAddress string) {
	var detailsStr *string
	if details != nil {
		b, err := json.Marshal(details)
		if err == nil {
			s := string(b)
			detailsStr = &s
		}
	}

	var ip *string
	if ipAddress != "" {
		ip = &ipAddress
	}

	entry := models.AuditLog{
		ActorID:    actorID,
		Action:     action,
		TargetType: targetType,
		TargetID:   targetID,
		Details:    detailsStr,
		IPAddress:  ip,
	}

	if err := database.DB.Create(&entry).Error; err != nil {
		log.Printf("[audit] Failed to write audit log: %v", err)
	}
}
