package resources

import (
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/pkg/agentcfg"
	"k8s.io/apimachinery/pkg/api/resource"
)

type objectQuantity struct {
	RequestsCPU              resource.Quantity
	RequestsMemory           resource.Quantity
	RequestsEphemeralStorage resource.Quantity
	LimitsCPU                resource.Quantity
	LimitsMemory             resource.Quantity
	LimitsEphemeralStorage   resource.Quantity
}

type quantity struct {
	CPU              resource.Quantity
	Memory           resource.Quantity
	EphemeralStorage resource.Quantity
}

// Manager is a struct that implements the Resources interface
type Manager struct {
	Requirements *agentcfg.ResourceRequirements
}

// Resources interface implements a way to provide a objectQuantity
// based on a resource requirement
type Resources interface {
	GetResources() (objectQuantity, error)
}

// GetResources returns a objectQuantity based on the ResourceRequirements of the manager
func (m *Manager) GetResources() (objectQuantity, error) {
	requestsResources, err := m.resources(m.Requirements.Requests)
	if err != nil {
		return objectQuantity{}, err
	}

	limitsResources, err := m.resources(m.Requirements.Limits)
	if err != nil {
		return objectQuantity{}, err
	}
	return objectQuantity{
		RequestsCPU:              requestsResources.CPU,
		RequestsMemory:           requestsResources.Memory,
		RequestsEphemeralStorage: requestsResources.EphemeralStorage,
		LimitsCPU:                limitsResources.CPU,
		LimitsMemory:             limitsResources.Memory,
		LimitsEphemeralStorage:   limitsResources.EphemeralStorage,
	}, nil
}

func (m *Manager) resources(resources *agentcfg.Resource) (quantity, error) {
	cpu, err := resource.ParseQuantity(resources.Cpu)
	if err != nil {
		return quantity{}, err
	}

	memory, err := resource.ParseQuantity(resources.Memory)
	if err != nil {
		return quantity{}, err
	}

	ephemeralStorage, err := resource.ParseQuantity(resources.EphemeralStorage)
	if err != nil {
		return quantity{}, err
	}

	return quantity{
		CPU:              cpu,
		Memory:           memory,
		EphemeralStorage: ephemeralStorage,
	}, nil
}
