package server

import (
	"encoding/json"
	"fmt"
	"io"
	"log/slog"
	"net/http"

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

func handleSync(bs *booking.Service) http.HandlerFunc {
	type BookingInfo struct {
		Content string `json:"content"`
	}

	return func(w http.ResponseWriter, r *http.Request) {
		slog.Info("received booking sync request from booking")
		body, err := io.ReadAll(r.Body)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer r.Body.Close()

		bookingInfo := new(BookingInfo)
		if err := json.Unmarshal(body, bookingInfo); err != nil {
			http.Error(w, fmt.Sprintf("error unmarshalling JSON: %s", err), http.StatusInternalServerError)
			return
		}

		b, err := bs.ParseFromAPI(bookingInfo.Content)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		slog.Info("created booking from API", slog.String("name", b.Name), slog.String("platform", string(b.Platform)))

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)
		if err := json.NewEncoder(w).Encode("👍"); err != nil {
			slog.Error("failed to write response", slog.Any("error", err))
		}
	}
}

func handleCreateBooking(bs *booking.Service) http.HandlerFunc {
	type BookingInfo struct {
		Content string `json:"content"`
	}

	return func(w http.ResponseWriter, r *http.Request) {
		slog.Info("received booking sync request from booking")
		body, err := io.ReadAll(r.Body)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer r.Body.Close()

		slog.Info("request body", slog.String("body", string(body)))

		bookingInfo := new(BookingInfo)
		if err := json.Unmarshal(body, bookingInfo); err != nil {
			http.Error(w, fmt.Sprintf("error unmarshalling JSON: %s", err), http.StatusInternalServerError)
			return
		}

		b, err := bs.ParseFromAPI(bookingInfo.Content)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		slog.Info("created booking from API", slog.String("name", b.Name), slog.String("platform", string(b.Platform)))

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)
		if err := json.NewEncoder(w).Encode("👍"); err != nil {
			slog.Error("failed to write response", slog.Any("error", err))
		}
	}
}
