package redis

import (
	"time"

	"forge.cadoles.com/cadoles/bouncer/internal/store"
	"github.com/pkg/errors"
)

type proxyHeaderItem struct {
	Name string `redis:"name"`

	Weight  int  `redis:"weight"`
	Enabled bool `redis:"enabled"`

	CreatedAt *jsonWrapper[time.Time] `redis:"created_at"`
	UpdatedAt *jsonWrapper[time.Time] `redis:"updated_at"`
}

func (i *proxyHeaderItem) ToProxyHeader() (*store.ProxyHeader, error) {
	proxyHeader := &store.ProxyHeader{
		Name:    store.ProxyName(i.Name),
		Weight:  i.Weight,
		Enabled: i.Enabled,
	}

	return proxyHeader, nil
}

type proxyItem struct {
	proxyHeaderItem
	To   string                 `redis:"to"`
	From *jsonWrapper[[]string] `redis:"from"`
}

func (i *proxyItem) ToProxy() (*store.Proxy, error) {
	proxyHeader, err := i.proxyHeaderItem.ToProxyHeader()
	if err != nil {
		return nil, errors.WithStack(err)
	}

	proxy := &store.Proxy{
		ProxyHeader: *proxyHeader,
		To:          i.To,
	}

	if i.CreatedAt != nil {
		proxy.CreatedAt = i.CreatedAt.Value()
	}

	if i.UpdatedAt != nil {
		proxy.UpdatedAt = i.UpdatedAt.Value()
	}

	if i.From != nil {
		proxy.From = i.From.Value()
	}

	return proxy, nil
}