package got

import (
	"fmt"
	"strings"

	. "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common"
	G "github.com/dave/jennifer/jen"
)

func GenMiddlewares(p *Project) (err error) {
	for _, middle := range Middlewares {
		if middle.Type == "middleware" {

			if err = CreateMiddleware(p, middle); err != nil {
				return err
			}
		}
	}
	return nil
}

func CreateMiddleware(p *Project, middle *Middleware) error {

	var (
		err  error
		file = G.NewFile(p.Package)
		ctx  = &MiddlewareContext{
			Project:    p,
			Middleware: middle,
			Statement: file.Func().Id(fmt.Sprintf("%sMiddleware", strings.Title(middle.Id))).Params(
				G.Id("ctx").Qual(IRIS_CTX, "Context"),
			),
		}
	)

	if err = middle.Fn(ctx); err != nil {
		return err
	}

	return Write(fmt.Sprintf("%s/%s/middleware_%s.go", p.OutPath, p.Package, middle.Id), file)
}
