package handlers

import (
	"encoding/json"
	"github.com/gorilla/mux"
	"go_project/internal/configuration"
	"go_project/internal/connection"
	"go_project/internal/controllers"
	"log"
	"net/http"
	"strconv"
)

func GetBookingById(response http.ResponseWriter, request *http.Request) {
	log.Println("GetBookingById Serving:", request.URL.Path, "from", request.Host)

	sqlHandler, err := connection.OpenDefault()
	if err != nil {
		log.Println("Error opening database connection:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer connection.MustClose(sqlHandler)

	requestVars := mux.Vars(request)
	bookingIdStringValue := requestVars["id"]

	id, err := strconv.Atoi(bookingIdStringValue)
	if err != nil {
		log.Println("Current id string value of the booking record to get: \"" + bookingIdStringValue + "\"")
		log.Println("Error parse id string value to int:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	booking, err := controllers.BookingById(sqlHandler, id)
	if err != nil {
		log.Println("Error getting booking by id from database:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	bookingMarshaled, err := json.Marshal(booking)
	if err != nil {
		log.Println("Error marshaling booking to json string format:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	response.Header().Set("Content-Type", "application/json")
	_, err = response.Write(bookingMarshaled)
	if err != nil {
		log.Println("Error writing booking to response:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}
	response.WriteHeader(http.StatusOK)
}

func GetAllBookings(response http.ResponseWriter, request *http.Request) {
	log.Println("GetAllBookings Serving:", request.URL.Path, "from", request.Host)

	sqlHandler, err := connection.OpenDefault()
	if err != nil {
		log.Println("Error opening database connection:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer connection.MustClose(sqlHandler)

	limit, offset := configuration.GetRecordsLimit(), configuration.GetRecordsOffset()
	listBookingParams := controllers.ListBookingParams{Limit: limit, Offset: offset}

	allBookings, err := controllers.AllBookings(sqlHandler, listBookingParams)
	if err != nil {
		log.Println("Error getting all bookings from database:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	allBookingsMarshaled, err := json.Marshal(allBookings)
	if err != nil {
		log.Println("Error marshaling all bookings:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	response.Header().Set("Content-Type", "application/json")
	_, err = response.Write(allBookingsMarshaled)
	if err != nil {
		log.Println("Error writing all bookings to response:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}
	response.WriteHeader(http.StatusOK)
}

func CreateBooking(response http.ResponseWriter, request *http.Request) {
	log.Println("CreateBooking Serving:", request.URL.Path, "from", request.Host)

	sqlHandler, err := connection.OpenDefault()
	if err != nil {
		log.Println("Error opening database connection:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer connection.MustClose(sqlHandler)

	var createBookingParams controllers.CreateBookingParams
	err = json.NewDecoder(request.Body).Decode(&createBookingParams)
	if err != nil {
		log.Println("CreateBooking: Values of createBookingParams:", createBookingParams)
		log.Println("Error unmarshaling booking from json string format:", err)
		response.WriteHeader(http.StatusBadRequest)
		return
	}

	newBooking, err := controllers.CreateBooking(sqlHandler, createBookingParams)
	if err != nil {
		log.Println("Error creating booking:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	newBookingMarshaled, err := json.Marshal(newBooking)
	if err != nil {
		log.Println("Error marshaling booking to json string format:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	response.Header().Set("Content-Type", "application/json")
	_, err = response.Write(newBookingMarshaled)
	if err != nil {
		log.Println("Error writing booking to response:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}
	response.WriteHeader(http.StatusOK)
}

func UpdateBooking(response http.ResponseWriter, request *http.Request) {
	log.Println("UpdateBookingById Serving:", request.URL.Path, "from", request.Host)

	sqlHandler, err := connection.OpenDefault()
	if err != nil {
		log.Println("Error opening database connection:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer connection.MustClose(sqlHandler)

	var updateBookingParams controllers.UpdateBookingParams
	err = json.NewDecoder(request.Body).Decode(&updateBookingParams)
	if err != nil {
		log.Println("UpdateBooking: Values of updateBookingParams:", updateBookingParams)
		log.Println("Error unmarshaling booking from json string format:", err)
		response.WriteHeader(http.StatusBadRequest)
		return
	}

	newBooking, err := controllers.UpdateBooking(sqlHandler, updateBookingParams)
	if err != nil {
		log.Println("Error updating booking by id from database:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	log.Println("SQL result: Updated booking record is:", newBooking)

	response.WriteHeader(http.StatusOK)
}

func DeleteBookingById(response http.ResponseWriter, request *http.Request) {
	log.Println("DeleteBookingById Serving:", request.URL.Path, "from", request.Host)

	sqlHandler, err := connection.OpenDefault()
	if err != err {
		log.Println("Error opening database connection:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer connection.MustClose(sqlHandler)

	requestVars := mux.Vars(request)
	bookingIdStringValue := requestVars["id"]

	id, err := strconv.Atoi(bookingIdStringValue)
	if err != nil {
		log.Println("Current id string value of the booking record to delete: \"" + bookingIdStringValue + "\"")
		log.Println("Error parse id string value to int:", err)
		response.WriteHeader(http.StatusBadRequest)
		return
	}

	sqlResult, err := controllers.DeleteBookingById(sqlHandler, id)
	if err != nil {
		log.Println("Error deleting booking by id from database:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	rowsAffected, err := sqlResult.RowsAffected()
	if err != nil {
		log.Println("Error getting number of rows affected by an delete:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	log.Println("SQL result: Number of rows affected by an delete:", rowsAffected)

	response.WriteHeader(http.StatusOK)
}
