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

package services

import (
	"context"
	"net/http"

	"dev.tandem.ws/tandem/camper/pkg/auth"
	"dev.tandem.ws/tandem/camper/pkg/carousel"
	"dev.tandem.ws/tandem/camper/pkg/database"
	httplib "dev.tandem.ws/tandem/camper/pkg/http"
	"dev.tandem.ws/tandem/camper/pkg/locale"
	"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 head string
		head, r.URL.Path = httplib.ShiftPath(r.URL.Path)
		switch head {
		case "":
			switch r.Method {
			case http.MethodGet:
				home := newServicesPage()
				home.MustRender(w, r, user, company, conn)
			default:
				httplib.MethodNotAllowed(w, r, http.MethodGet)
			}
		default:
			http.NotFound(w, r)
		}
	})
}

type servicesPage struct {
	*template.PublicPage
	Services []*service
	Carousel []*carousel.Slide
}

func newServicesPage() *servicesPage {
	return &servicesPage{PublicPage: template.NewPublicPage()}
}

func (p *servicesPage) MustRender(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
	p.Setup(r, user, company, conn)
	p.Services = mustCollectServices(r.Context(), company, conn, user.Locale)
	p.Carousel = carousel.MustCollectSlides(r.Context(), company, conn, user.Locale, carouselName)
	template.MustRenderPublic(w, r, user, company, "services.gohtml", p)
}

type service struct {
	IconName    string
	Name        string
	Description string
}

func mustCollectServices(ctx context.Context, company *auth.Company, conn *database.Conn, loc *locale.Locale) []*service {
	rows, err := conn.Query(ctx, `
		select icon_name
		     , coalesce(i18n.name, service.name) as l10_name
		     , coalesce(i18n.description, service.description)::text as l10_description
		from service
		    left join service_i18n as i18n on service.service_id = i18n.service_id and lang_tag = $1
		where service.company_id = $2
		order by position
		       , l10_name
	`, loc.Language, company.ID)
	if err != nil {
		panic(err)
	}
	defer rows.Close()

	var items []*service
	for rows.Next() {
		item := &service{}
		err = rows.Scan(&item.IconName, &item.Name, &item.Description)
		if err != nil {
			panic(err)
		}
		items = append(items, item)
	}
	if rows.Err() != nil {
		panic(rows.Err())
	}

	return items
}