package audit

import (
	"context"
	"encoding/json"

	"github.com/google/uuid"
)

type Entry struct {
	ActorUserID *uuid.UUID
	EntityType  string
	EntityID    *uuid.UUID
	EventType   string
	Status      string
	Message     string
	Metadata    map[string]any
}

type Repository interface {
	Write(ctx context.Context, entry Entry) error
	List(ctx context.Context, limit int) ([]map[string]any, error)
}

type Service struct {
	repo Repository
}

func NewService(repo Repository) *Service {
	return &Service{repo: repo}
}

func (s *Service) Record(ctx context.Context, entry Entry) error {
	if entry.Metadata == nil {
		entry.Metadata = map[string]any{}
	}
	return s.repo.Write(ctx, entry)
}

func (s *Service) List(ctx context.Context, limit int) ([]map[string]any, error) {
	return s.repo.List(ctx, limit)
}

func MarshalMetadata(metadata map[string]any) []byte {
	raw, _ := json.Marshal(metadata)
	return raw
}
