package securityaudit

import (
	"context"
	"encoding/json"
	"log/slog"

	"github.com/jackc/pgx/v5/pgxpool"
)

const (
	ActionLogin            = "login"
	ActionTokenRejected    = "token_rejected"
	ActionAdminAction      = "admin_action"
	ActionCriticalDeletion = "critical_deletion"
)

type Logger struct {
	db     *pgxpool.Pool
	logger *slog.Logger
}

func NewLogger(db *pgxpool.Pool) *Logger {
	return &Logger{
		db:     db,
		logger: slog.Default().With("component", "security-audit"),
	}
}

func (l *Logger) Log(ctx context.Context, actor, action string, details map[string]any) {
	if l == nil || l.db == nil {
		return
	}
	if actor == "" {
		actor = "system"
	}
	if details == nil {
		details = map[string]any{}
	}

	detailsJSON, err := json.Marshal(details)
	if err != nil {
		l.logger.Error("marshal audit details", "error", err)
		return
	}

	if _, err := l.db.Exec(ctx, `
		INSERT INTO audit_logs (actor, action, details) VALUES ($1, $2, $3)
	`, actor, action, detailsJSON); err != nil {
		l.logger.Error("insert audit log", "error", err, "actor", actor, "action", action)
	}
}
