/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package types

import (
	"context"
	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"
	"dev.tandem.ws/tandem/camper/pkg/uuid"
)

type PublicHandler struct {
}

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 head string
		head, r.URL.Path = httplib.ShiftPath(r.URL.Path)

		switch r.Method {
		case http.MethodGet:
			if !uuid.Valid(head) {
				http.NotFound(w, r)
				return
			}
			page, err := newPublicPage(r.Context(), conn, head)
			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)
		}
	})
}

type publicPage struct {
	*template.PublicPage
	Name        string
	Description gotemplate.HTML
}

func newPublicPage(ctx context.Context, conn *database.Conn, slug string) (*publicPage, error) {
	page := &publicPage{
		PublicPage: template.NewPublicPage(),
	}
	row := conn.QueryRow(ctx, "select name, description::text from campsite_type where slug = $1 and active", slug)
	if err := row.Scan(&page.Name, &page.Description); err != nil {
		return nil, err
	}

	return page, nil
}

func (p *publicPage) 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, "campsite/type.gohtml", p)
}
