package server

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

	"github.com/go-chi/chi/v5"
	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) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		idStr := chi.URLParam(r, "id")
		id, err := strconv.Atoi(idStr)
		if err != nil {
			http.Error(w, "invalid booking id", http.StatusBadRequest)
			return
		}

		b := bs.One(id)

		filePath, err := bs.BuildInvoice(b, hc)
		if err != nil {
			slog.Error("failed to build invoice", slog.Any("error", err))
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		http.ServeFile(w, r, filePath)
	}
}

func handlePdfCreateReport(bs *booking.Service) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		period := r.URL.Query().Get("period")
		if !u.Contains([]string{"month", "year"}, period) {
			http.Error(w, fmt.Sprintf("%q is not a valid period", period), http.StatusBadRequest)
			return
		}

		monthStr := r.URL.Query().Get("month")
		month, err := strconv.Atoi(monthStr)
		if err != nil || month < 1 || month > 12 {
			http.Error(w, fmt.Sprintf("%q is not a valid month", monthStr), http.StatusBadRequest)
			return
		}

		yearStr := r.URL.Query().Get("year")
		year, err := strconv.Atoi(yearStr)
		if err != nil {
			http.Error(w, fmt.Sprintf("%q is not a valid year", yearStr), http.StatusBadRequest)
			return
		}

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

		http.ServeFile(w, r, filePath)
	}
}
