package server

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

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

	"github.com/rjNemo/rentease/internal/config"
	"github.com/rjNemo/rentease/internal/service/booking"
)

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

		b := bs.One(id)

		err = bs.BuildInvoice(b, hc)
		if err != nil {
			return err
		}
		return c.Attachment("tmp.pdf", fmt.Sprintf("VFNI-%s.pdf", b.InvoiceNumber(hc)))
	}
}

func handlePdfCreateReport(bs *booking.Service) echo.HandlerFunc {
	return func(c echo.Context) error {
		period := c.QueryParam("period")
		if !u.Contains([]string{"month", "year"}, period) {
			return &echo.HTTPError{
				Code:    http.StatusBadRequest,
				Message: fmt.Sprintf("%q is not a valid period", period),
			}
		}

		monthStr := c.QueryParam("month")
		month, err := strconv.Atoi(monthStr)
		if err != nil || month < 1 || month > 12 {
			return &echo.HTTPError{
				Code:    http.StatusBadRequest,
				Message: fmt.Sprintf("%q is not a valid month", month),
			}
		}

		yearStr := c.QueryParam("year")
		year, err := strconv.Atoi(yearStr)
		if err != nil {
			return &echo.HTTPError{
				Code:    http.StatusBadRequest,
				Message: fmt.Sprintf("%q is not a valid year", year),
			}
		}

		report := bs.Report(period, month, year)
		err = bs.BuildReport(report, period, month, year)
		if err != nil {
			return err
		}

		return c.Attachment("tmp.pdf", fmt.Sprintf("VF-%02d-report.pdf", month))
	}
}
