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

package booking

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

type paymentPage struct {
	*template.PublicPage
	Environment string
	Request     *redsys.SignedRequest
}

func newPaymentPage(request *redsys.SignedRequest) *paymentPage {
	return &paymentPage{
		PublicPage: template.NewPublicPage(),
		Request:    request,
	}
}

func (p *paymentPage) MustRender(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
	p.Setup(r, user, company, conn)
	if err := conn.QueryRow(r.Context(), "select environment from redsys where company_id = $1", company.ID).Scan(&p.Environment); err != nil && !database.ErrorIsNotFound(err) {
		panic(err)
	}
	template.MustRenderPublic(w, r, user, company, "payment/request.gohtml", p)
}

func handleSuccessfulPayment(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
	var head string
	head, r.URL.Path = httplib.ShiftPath(r.URL.Path)

	switch head {
	case "":
		switch r.Method {
		case http.MethodGet:
			page := newSuccessfulPaymentPage()
			page.MustRender(w, r, user, company, conn)
		default:
			httplib.MethodNotAllowed(w, r, http.MethodGet, http.MethodPost)
		}
	default:
		http.NotFound(w, r)
	}
}

type successfulPaymentPage struct {
	*template.PublicPage
}

func newSuccessfulPaymentPage() *successfulPaymentPage {
	return &successfulPaymentPage{
		PublicPage: template.NewPublicPage(),
	}
}

func (p *successfulPaymentPage) 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, "payment/success.gohtml", p)
}

func handleFailedPayment(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
	var head string
	head, r.URL.Path = httplib.ShiftPath(r.URL.Path)

	switch head {
	case "":
		switch r.Method {
		case http.MethodGet:
			page := newFailedPaymentPage()
			page.MustRender(w, r, user, company, conn)
		default:
			httplib.MethodNotAllowed(w, r, http.MethodGet, http.MethodPost)
		}
	default:
		http.NotFound(w, r)
	}
}

type failedPaymentPage struct {
	*template.PublicPage
}

func newFailedPaymentPage() *failedPaymentPage {
	return &failedPaymentPage{
		PublicPage: template.NewPublicPage(),
	}
}

func (p *failedPaymentPage) 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, "payment/failure.gohtml", p)
}
