package utils

import (
	"context"
	"fmt"
	"os"
	"time"

	"pluja.dev/kycnot.me/ent"
)

// Getenv returns the value of the environment variable named by the key if exists,
// otherwise, it returns the fallback value.
func Getenv(key, fallback string) string {
	if value, ok := os.LookupEnv(key); ok {
		return value
	}

	return fallback
}

// Given a service and an action, add the action to the service's update actions
// It will also remove the oldest action if there are more than 10
func AddServiceUpdateActions(s *ent.Service, action string) error {
	action = fmt.Sprintf("%v: %v", time.Now().Format("2006-01-02 15:04:05"), action)
	if len(s.UpdateActions) == 0 {
		s.UpdateActions = []string{action}
	} else {
		s.UpdateActions = append(s.UpdateActions, action)
	}

	// If more than 10 actions, remove the oldest one
	if len(s.UpdateActions) > 10 {
		s.UpdateActions = s.UpdateActions[1:]
	}

	_, err := s.Update().SetUpdateActions(s.UpdateActions).Save(context.Background())
	return err
}
