package server

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/labstack/echo/v4"
	u "github.com/rjNemo/underscore"

	"github.com/rjNemo/rentease/internal/constant"
	"github.com/rjNemo/rentease/internal/service/booking"
	"github.com/rjNemo/rentease/internal/view"
)

func handleCreatePayment(bs *booking.Service) echo.HandlerFunc {
	type CreatePaymentInput struct {
		Amount        float64 `form:"amount"`
		PaymentMethod string  `form:"paymentMethod"`
	}

	return func(c echo.Context) error {
		idStr := c.Param("id")
		id, err := strconv.Atoi(idStr)
		if err != nil {
			return err
		}

		np := new(CreatePaymentInput)
		if err := c.Bind(np); err != nil {
			return err
		}

		b := bs.One(id)

		_, err = bs.CreatePayment(b.Id, np.Amount, np.PaymentMethod)
		if err != nil {
			return err
		}

		nb := bs.One(id)

		return renderTempl(c, http.StatusOK, view.PaymentList(
			u.Map(nb.Payments, func(p booking.Payment) *view.PaymentViewModel {
				return &view.PaymentViewModel{
					Amount:        strconv.FormatFloat(p.Amount, 'f', 2, 64),
					PaymentMethod: p.PaymentMethod,
					PaymentUrl:    fmt.Sprintf("%s/%d", constant.RoutePayment, p.ID),
				}
			}),
		))
	}
}

func handlePaymentForm(bs *booking.Service) echo.HandlerFunc {
	return func(c echo.Context) error {
		idStr := c.Param("id")
		id, err := strconv.Atoi(idStr)
		if err != nil {
			return err
		}

		p := bs.OnePayment(id)
		form := view.PaymentForm(&view.PaymentViewModel{
			Amount:        strconv.FormatFloat(p.Amount, 'f', 2, 64),
			PaymentMethod: p.PaymentMethod,
			PaymentUrl:    fmt.Sprintf("%s/%d", constant.RoutePayment, p.ID),
		})
		return renderTempl(c, http.StatusOK, form)
	}
}
