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 GetAllTables(response http.ResponseWriter, request *http.Request) {
	log.Println("GetAllTables 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()
	listTableParams := controllers.ListTableParams{Limit: limit, Offset: offset}

	allTables, err := controllers.AllTables(sqlHandler, listTableParams)
	if err != nil {
		log.Println("Error getting all tables from database:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

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

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

func GetTableById(response http.ResponseWriter, request *http.Request) {
	log.Println("GetTableById 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)
	tableIdStringValue := requestVars["id"]

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

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

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

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

func CreateTable(response http.ResponseWriter, request *http.Request) {
	log.Println("CreateTable 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 createTableParams controllers.CreateTableParams
	err = json.NewDecoder(request.Body).Decode(&createTableParams)
	if err != nil {
		log.Println("CreateTable: Values of createTableParams:", createTableParams)
		log.Println("Error unmarshaling table from json string format:", err)
		response.WriteHeader(http.StatusBadRequest)
		return
	}

	newTable, err := controllers.CreateTable(sqlHandler, createTableParams)
	if err != nil {
		log.Println("Error creating table:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

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

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

func DeleteTableById(response http.ResponseWriter, request *http.Request) {
	log.Println("DeleteTableById 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)
	tableIdStringValue := requestVars["id"]

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

	sqlResult, err := controllers.DeleteTableById(sqlHandler, id)
	if err != nil {
		log.Println("Error deleting table 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)
}

func UpdateTable(response http.ResponseWriter, request *http.Request) {
	log.Println("UpdateTableById 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 updateTableParams controllers.UpdateTableParams
	err = json.NewDecoder(request.Body).Decode(&updateTableParams)
	if err != nil {
		log.Println("UpdateTable: Values of updateTableParams:", updateTableParams)
		log.Println("Error unmarshaling table from json string format:", err)
		response.WriteHeader(http.StatusBadRequest)
		return
	}

	newTable, err := controllers.UpdateTable(sqlHandler, updateTableParams)
	if err != nil {
		log.Println("Error updating table by id from database:", err)
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	log.Println("SQL result: Updated table record is:", newTable)

	response.WriteHeader(http.StatusOK)
}
