package routers

import (
	"github.com/go-chi/chi/v5"
	api "github.com/tech/sendico/pkg/api/http"
	"github.com/tech/sendico/pkg/db/account"
	"github.com/tech/sendico/pkg/db/refreshtokens"
	"github.com/tech/sendico/pkg/db/verification"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/mservice"
	"github.com/tech/sendico/server/interface/api/sresponse"
	"github.com/tech/sendico/server/interface/middleware"
	re "github.com/tech/sendico/server/internal/api/routers/endpoint"
)

type PublicRouter struct {
	logger    mlogger.Logger
	db        account.DB
	imp       *re.HttpEndpointRouter
	rtdb      refreshtokens.DB
	config    middleware.TokenConfig
	signature middleware.Signature
	service   mservice.Type
}

func (pr *PublicRouter) InstallHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.HandlerFunc) {
	pr.imp.InstallHandler(service, endpoint, method, handler)
}

func NewRouter(logger mlogger.Logger, apiEndpoint string, db account.DB, vdb verification.DB, rtdb refreshtokens.DB, router chi.Router, config *middleware.TokenConfig, signature *middleware.Signature) *PublicRouter {
	l := logger.Named("public")
	hr := PublicRouter{
		logger:    l,
		db:        db,
		rtdb:      rtdb,
		config:    *config,
		signature: *signature,
		imp:       re.NewHttpEndpointRouter(l, apiEndpoint, router, config, signature),
		service:   mservice.Accounts,
	}

	hr.InstallHandler(hr.service, "/login", api.Post, hr.login)
	hr.InstallHandler(hr.service, "/login/api", api.Post, hr.apiLogin)
	hr.InstallHandler(hr.service, "/rotate", api.Post, hr.rotateRefreshToken)
	hr.InstallHandler(hr.service, "/refresh", api.Post, hr.refreshAccessToken)

	return &hr
}
