package builderimp

import (
	"strings"

	"github.com/tech/sendico/pkg/db/repository/builder"
)

type FieldImp struct {
	fields []string
}

func (b *FieldImp) Dot(field string) builder.Field {
	newFields := make([]string, len(b.fields), len(b.fields)+1)
	copy(newFields, b.fields)
	newFields = append(newFields, field)
	return &FieldImp{fields: newFields}
}

func (b *FieldImp) CopyWith(field string) builder.Field {
	copiedFields := make([]string, 0, len(b.fields)+1)
	copiedFields = append(copiedFields, b.fields...)
	copiedFields = append(copiedFields, field)
	return &FieldImp{
		fields: copiedFields,
	}
}

func (b *FieldImp) Build() string {
	return strings.Join(b.fields, ".")
}

func NewFieldImp(baseName string) builder.Field {
	return &FieldImp{
		fields: []string{baseName},
	}
}

type RefField struct {
	imp builder.Field
}

func (b *RefField) Build() string {
	return "$" + b.imp.Build()
}

func (b *RefField) CopyWith(field string) builder.Field {
	return &RefField{
		imp: b.imp.CopyWith(field),
	}
}

func (b *RefField) Dot(field string) builder.Field {
	return &RefField{
		imp: b.imp.Dot(field),
	}
}

func NewRefFieldImp(field builder.Field) builder.Field {
	return &RefField{
		imp: field,
	}
}

func NewRootRef() builder.Field {
	return NewFieldImp("$$ROOT")
}

func NewRemoveRef() builder.Field {
	return NewFieldImp("$$REMOVE")
}
