package api

import (
	"encoding/json"

	"github.com/alexei/tinyforge/internal/store"
	"github.com/alexei/tinyforge/internal/workload/plugin"
)

// toPluginWorkload is a local alias for the shared plugin.WorkloadFromStore
// converter, kept so the api package's many call sites read tersely and pair
// visually with fromPluginWorkload below. The conversion logic lives in the
// plugin package (the single home shared with reconciler / webhook).
func toPluginWorkload(w store.Workload) plugin.Workload {
	return plugin.WorkloadFromStore(w)
}

// fromPluginWorkload is the symmetric direction — used by /api/workloads
// create + update handlers. Returns a store.Workload ready to pass to
// store.CreateWorkload / store.UpdateWorkload. The caller is responsible
// for re-encoding PublicFaces; we do it here to keep the JSON shape in
// one place.
func fromPluginWorkload(p plugin.Workload) (store.Workload, error) {
	facesJSON := "[]"
	if len(p.PublicFaces) > 0 {
		b, err := json.Marshal(p.PublicFaces)
		if err != nil {
			return store.Workload{}, err
		}
		facesJSON = string(b)
	}
	srcCfg := string(p.SourceConfig)
	if srcCfg == "" {
		srcCfg = "{}"
	}
	trgCfg := string(p.TriggerConfig)
	if trgCfg == "" {
		trgCfg = "{}"
	}
	return store.Workload{
		ID:                      p.ID,
		Name:                    p.Name,
		AppID:                   p.GroupID,
		ParentWorkloadID:        p.ParentWorkloadID,
		SourceKind:              p.SourceKind,
		SourceConfig:            srcCfg,
		TriggerKind:             p.TriggerKind,
		TriggerConfig:           trgCfg,
		PublicFaces:             facesJSON,
		NotificationURL:         p.NotificationURL,
		NotificationSecret:      p.NotificationSecret,
		WebhookSecret:           p.WebhookSecret,
		WebhookSigningSecret:    p.WebhookSigningSecret,
		WebhookRequireSignature: p.WebhookRequireSignature,
		CreatedAt:               p.CreatedAt,
		UpdatedAt:               p.UpdatedAt,
	}, nil
}
