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

package booking

import (
	"fmt"
	"net/http"

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

func requestPayment(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
	f, err := newBookingForm(r, company, conn, user.Locale)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if ok, err := f.Valid(r.Context(), conn, user.Locale); err != nil {
		panic(err)
	} else if !ok {
		if !httplib.IsHTMxRequest(r) {
			w.WriteHeader(http.StatusUnprocessableEntity)
		}
		page := newPublicPageWithForm(f)
		page.HasErrors = true
		page.MustRender(w, r, user, company, conn)
		return
	}

	_, err = conn.ReadyPayment(
		r.Context(),
		f.PaymentSlug.Val,
		f.Customer.FullName.Val,
		f.Customer.Address.Val,
		f.Customer.PostalCode.Val,
		f.Customer.City.Val,
		f.Customer.Country.String(),
		f.Customer.Email.Val,
		f.Customer.Phone.Val,
		user.Locale.Language,
	)
	if err != nil {
		panic(err)
	}
	httplib.Redirect(w, r, fmt.Sprintf("/%s/payments/%s", user.Locale.Language, f.PaymentSlug.Val), http.StatusSeeOther)
}
