package legal

import (
	"context"
	"dev.tandem.ws/tandem/camper/pkg/locale"
	gotemplate "html/template"
	"net/http"

	"dev.tandem.ws/tandem/camper/pkg/auth"
	"dev.tandem.ws/tandem/camper/pkg/database"
	httplib "dev.tandem.ws/tandem/camper/pkg/http"
	"dev.tandem.ws/tandem/camper/pkg/template"
)

type PublicHandler struct {
}

func NewPublicHandler() *PublicHandler {
	return &PublicHandler{}
}

func (h *PublicHandler) Handler(user *auth.User, company *auth.Company, conn *database.Conn) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var slug string
		slug, r.URL.Path = httplib.ShiftPath(r.URL.Path)

		var head string
		head, r.URL.Path = httplib.ShiftPath(r.URL.Path)

		switch head {
		case "":
			switch r.Method {
			case http.MethodGet:
				page, err := newLegalPage(r.Context(), company, conn, user.Locale, slug)
				if database.ErrorIsNotFound(err) {
					http.NotFound(w, r)
					return
				} else if err != nil {
					panic(err)
				}
				page.MustRender(w, r, user, company, conn)
			default:
				httplib.MethodNotAllowed(w, r, http.MethodGet)
			}
		default:
			http.NotFound(w, r)
		}
	})
}

type legalPage struct {
	*template.PublicPage
	Name    string
	Content gotemplate.HTML
}

func newLegalPage(ctx context.Context, company *auth.Company, conn *database.Conn, loc *locale.Locale, slug string) (*legalPage, error) {
	page := &legalPage{
		PublicPage: template.NewPublicPage(),
	}
	row := conn.QueryRow(ctx, `
		select coalesce(i18n.name, text.name) as l10n_name
		     , coalesce(i18n.content, text.content)::text as l10n_description
		from legal_text as text
		    left join legal_text_i18n as i18n on text.company_id = i18n.company_id and text.slug = i18n.slug and i18n.lang_tag = $1
		where text.company_id = $2
		  and text.slug = $3
	`, loc.Language, company.ID, slug)
	if err := row.Scan(&page.Name, &page.Content); err != nil {
		return nil, err
	}
	return page, nil
}

func (p *legalPage) MustRender(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
	p.Setup(r, user, company, conn)
	template.MustRenderPublic(w, r, user, company, "legal.gohtml", p)
}
