package rest

import (
	"git.nspix.com/golang/micro/gateway/http"
	"gorm.io/gorm"
	"strings"
)

type Options struct {
	EnableNamespace   bool
	Namespace         string
	DB                *gorm.DB
	Prefix            string
	TablePrefixes     []string
	RemoveTablePrefix bool
	Formatter         *Formatter
	Middleware        []http.Middleware
	MigrateOptions    *MigrateOptions
}

type Option func(o *Options)

func WithMigration(ops ...MigrateOption) Option {
	return func(o *Options) {
		if o.MigrateOptions == nil {
			o.MigrateOptions = &MigrateOptions{}
		}
		for _, f := range ops {
			f(o.MigrateOptions)
		}
	}
}

func WithPrefix(prefix string) Option {
	return func(o *Options) {
		if !strings.HasPrefix(prefix, "/") {
			prefix = "/" + prefix
		}
		if strings.HasSuffix(prefix, "/") {
			prefix = strings.TrimSuffix(prefix, "/")
		}
		o.Prefix = prefix
	}
}

func WithNamespace(namespace string) Option {
	return func(o *Options) {
		o.Namespace = namespace
	}
}

func WithDB(db *gorm.DB) Option {
	return func(o *Options) {
		o.DB = db
	}
}

func NewOptions() *Options {
	return &Options{
		Namespace:      DefaultNamespace,
		Formatter:      DefaultFormatter,
		Middleware:     make([]http.Middleware, 0),
		MigrateOptions: &MigrateOptions{},
	}
}
