package services

import (
	"context"
	"time"

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

func StoreInventory(serverID string, r *pb.InventoryReport) error {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	now := time.Now()
	set := bson.M{"inventory.metrics_at": now}
	if r.CPU != nil {
		set["inventory.cpu.usage_pct"] = r.CPU.UsagePct
		set["inventory.cpu.load1"] = r.CPU.Load1
	}
	if r.Memory != nil {
		set["inventory.memory.used_bytes"] = r.Memory.UsedBytes
	}
	set["inventory.swap_used_bytes"] = r.SwapUsed

	if r.IncludeStatic {
		set["inventory.static_at"] = now
		set["inventory.swap_total_bytes"] = r.SwapTotal
		set["inventory.kernel"] = r.Kernel
		if r.CPU != nil {
			set["inventory.cpu.model"] = r.CPU.Model
			set["inventory.cpu.cores"] = r.CPU.Cores
		}
		if r.Memory != nil {
			set["inventory.memory.total_bytes"] = r.Memory.TotalBytes
		}
		parts := make([]bson.M, 0, len(r.Partitions))
		for _, p := range r.Partitions {
			parts = append(parts, bson.M{
				"device": p.Device, "mountpoint": p.Mountpoint, "fstype": p.Fstype,
				"total_bytes": p.TotalBytes, "used_bytes": p.UsedBytes,
			})
		}
		set["inventory.partitions"] = parts
	}

	_, err := db.Col("servers").UpdateOne(ctx, bson.M{"server_id": serverID}, bson.M{"$set": set})
	return err
}
