package pkg

import (
	"net/http"

	"github.com/julienschmidt/httprouter"
)

func NewRouter(db *Db) http.Handler {
	companyRouter := httprouter.New()
	companyRouter.GET("/profile", GetProfileForm)
	companyRouter.POST("/profile", HandleProfileForm)
	companyRouter.GET("/tax-details", GetCompanyTaxDetailsForm)
	companyRouter.POST("/tax-details", HandleCompanyTaxDetailsForm)
	companyRouter.POST("/tax", HandleAddCompanyTax)
	companyRouter.DELETE("/tax/:taxId", HandleDeleteCompanyTax)
	companyRouter.GET("/contacts", IndexContacts)
	companyRouter.POST("/contacts", HandleAddContact)
	companyRouter.GET("/contacts/:slug", GetContactForm)
	companyRouter.PUT("/contacts/:slug", HandleUpdateContact)
	companyRouter.GET("/products", IndexProducts)
	companyRouter.POST("/products", HandleAddProduct)
	companyRouter.GET("/products/:slug", GetProductForm)
	companyRouter.PUT("/products/:slug", HandleUpdateProduct)
	companyRouter.GET("/invoices", IndexInvoices)
	companyRouter.POST("/invoices", HandleAddInvoice)
	companyRouter.GET("/invoices/:slug", GetInvoiceForm)
	companyRouter.POST("/invoices/new/products", HandleAddProductsToInvoice)
	companyRouter.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		mustRenderAppTemplate(w, r, "dashboard.gohtml", nil)
	})

	router := httprouter.New()
	router.ServeFiles("/static/*filepath", http.Dir("web/static"))
	router.GET("/login", GetLoginForm)
	router.POST("/login", HandleLoginForm)
	router.POST("/logout", Authenticated(HandleLogout))

	companyHandler := Authenticated(CompanyHandler(companyRouter))
	router.GET("/company/:slug/*rest", companyHandler)
	router.POST("/company/:slug/*rest", companyHandler)
	router.PUT("/company/:slug/*rest", companyHandler)
	router.DELETE("/company/:slug/*rest", companyHandler)

	router.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		user := getUser(r)
		if user.LoggedIn {
			conn := getConn(r)
			company := &Company{
				Slug: conn.MustGetText(r.Context(), "", "select slug::text from company order by company_id limit 1"),
			}
			http.Redirect(w, r, companyURI(company, "/"), http.StatusFound)
		} else {
			http.Redirect(w, r, "/login", http.StatusSeeOther)
		}
	})

	var handler http.Handler = router
	handler = MethodOverrider(handler)
	handler = LocaleSetter(db, handler)
	handler = LoginChecker(db, handler)
	handler = Recoverer(handler)
	handler = Logger(handler)
	return handler
}

func MethodOverrider(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodPost {
			if err := r.ParseForm(); err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
			override := r.FormValue(overrideMethodName)
			if override == http.MethodDelete || override == http.MethodPut {
				r2 := new(http.Request)
				*r2 = *r
				r2.Method = override
				r = r2
			}
		}
		next.ServeHTTP(w, r)
	})
}
