package builderimp

import (
	"time"

	"github.com/tech/sendico/pkg/db/repository/builder"
	"github.com/tech/sendico/pkg/db/storable"
	"go.mongodb.org/mongo-driver/v2/bson"
)

type patchBuilder struct {
	updates bson.D
}

func set(field builder.Field, value any) bson.E {
	return bson.E{Key: string(builder.Set), Value: bson.D{{Key: field.Build(), Value: value}}}
}

func (u *patchBuilder) Set(field builder.Field, value any) builder.Patch {
	u.updates = append(u.updates, set(field, value))
	return u
}

func (u *patchBuilder) Inc(field builder.Field, value any) builder.Patch {
	u.updates = append(u.updates, bson.E{Key: string(builder.Inc), Value: bson.D{{Key: field.Build(), Value: value}}})
	return u
}

func (u *patchBuilder) Unset(field builder.Field) builder.Patch {
	u.updates = append(u.updates, bson.E{Key: string(builder.Unset), Value: bson.D{{Key: field.Build(), Value: ""}}})
	return u
}

func (u *patchBuilder) Rename(field builder.Field, newName string) builder.Patch {
	u.updates = append(u.updates, bson.E{Key: string(builder.Rename), Value: bson.D{{Key: field.Build(), Value: newName}}})
	return u
}

func (u *patchBuilder) Push(field builder.Field, value any) builder.Patch {
	u.updates = append(u.updates, bson.E{Key: string(builder.Push), Value: bson.D{{Key: field.Build(), Value: value}}})
	return u
}

func (u *patchBuilder) Pull(field builder.Field, value any) builder.Patch {
	u.updates = append(u.updates, bson.E{Key: string(builder.Pull), Value: bson.D{{Key: field.Build(), Value: value}}})
	return u
}

func (u *patchBuilder) AddToSet(field builder.Field, value any) builder.Patch {
	u.updates = append(u.updates, bson.E{Key: string(builder.AddToSet), Value: bson.D{{Key: field.Build(), Value: value}}})
	return u
}

func (u *patchBuilder) Build() bson.D {
	return append(u.updates, set(NewFieldImp(storable.UpdatedAtField), time.Now()))
}

func NewPatchImp() builder.Patch {
	return &patchBuilder{updates: bson.D{}}
}
