package services

import (
	"context"
	"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"
)

func BuildAuthorizedKeys(serverID string) ([]string, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	srv, err := getServerByID(serverID)
	if err != nil {
		return nil, err
	}

	cursor, err := db.Col("assignments").Find(ctx, bson.M{
		"instance_id": srv.InstanceID,
		"server_id":   serverID,
		"revoked_at":  nil,
	})
	if err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)

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

	var lines []string
	for _, a := range assignments {
		var key models.Key
		err := db.Col("keys").FindOne(ctx, bson.M{"key_id": a.KeyID, "instance_id": srv.InstanceID}).Decode(&key)
		if err != nil {
			continue
		}
		lines = append(lines, key.PublicKey)
	}
	return lines, nil
}
