package routing

import (
	"encoding/json"

	"chat-switchboard/models"
)

// FromModel converts a DB model to a routing Policy for evaluation.
func FromModel(m *models.RoutingPolicy) Policy {
	p := Policy{
		ID:       m.ID,
		Name:     m.Name,
		Scope:    m.Scope,
		TeamID:   m.TeamID,
		Priority: m.Priority,
		Type:     PolicyType(m.Type),
		IsActive: m.IsActive,
		CreatedAt: m.CreatedAt,
		UpdatedAt: m.UpdatedAt,
	}

	// Convert JSONMap → PolicyConfig via JSON round-trip.
	// This is safe because PolicyConfig fields match the JSONB keys.
	if m.Config != nil {
		raw, _ := json.Marshal(m.Config)
		json.Unmarshal(raw, &p.Config)
	}

	return p
}

// FromModels converts a slice of DB models to routing Policies.
func FromModels(ms []models.RoutingPolicy) []Policy {
	out := make([]Policy, len(ms))
	for i := range ms {
		out[i] = FromModel(&ms[i])
	}
	return out
}
