package services

import (
	"context"
	"log"
	"time"

	"gitea.hostxtra.co.uk/mrhid6/vantage/server/internal/db"
	"gitea.hostxtra.co.uk/mrhid6/vantage/server/internal/models"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func LogEvent(instanceID, eventType, actor, serverID, keyID, details string) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	event := models.AuditEvent{
		InstanceID: instanceID,
		EventType:  eventType,
		Actor:      actor,
		ServerID:   serverID,
		KeyID:      keyID,
		Details:    details,
		CreatedAt:  time.Now(),
	}
	if _, err := db.Col("audit_logs").InsertOne(ctx, event); err != nil {
		log.Printf("audit log error: %v", err)
	}
}

func ListAuditEvents(instanceID string, limit int64) ([]models.AuditEvent, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	opts := options.Find().
		SetSort(bson.D{{Key: "created_at", Value: -1}}).
		SetLimit(limit)

	cursor, err := db.Col("audit_logs").Find(ctx, bson.M{"instance_id": instanceID}, opts)
	if err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)

	var events []models.AuditEvent
	if err := cursor.All(ctx, &events); err != nil {
		return nil, err
	}
	return events, nil
}
