package handler

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
	"vctp/db/queries"
	models "vctp/server/models"
)

// VmUpdate receives the CloudEvent for a VM modification or move
func (h *Handler) VmDelete(w http.ResponseWriter, r *http.Request) {
	var (
		deletedTimestamp int64
	)

	reqBody, err := io.ReadAll(r.Body)
	if err != nil {
		h.Logger.Error("Invalid data received", "error", err)
		fmt.Fprintf(w, "Invalid data received")
		w.WriteHeader(http.StatusInternalServerError)
		return
	} else {
		h.Logger.Debug("received input data", "length", len(reqBody))
	}

	// Decode the JSON body into CloudEventReceived struct
	var event models.CloudEventReceived
	if err := json.Unmarshal(reqBody, &event); err != nil {
		h.Logger.Error("unable to decode json", "error", err)
		prettyPrint(event)
		http.Error(w, "Invalid JSON body", http.StatusBadRequest)
		return
	} else {
		h.Logger.Debug("successfully decoded JSON")
	}

	// Use the event CreatedTime to update the DeletionTime column in the VM inventory table
	// Parse the datetime string to a time.Time object
	eventTime, err := time.Parse(time.RFC3339, event.CloudEvent.Data.CreatedTime)
	if err != nil {
		h.Logger.Warn("unable to convert cloud event time to timestamp", "error", err)
		deletedTimestamp = time.Now().Unix()
	} else {
		// Convert to Unix timestamp
		deletedTimestamp = eventTime.Unix()
	}

	// create the database parameters
	params := queries.InventoryMarkDeletedParams{
		DeletionTime:   sql.NullInt64{Int64: deletedTimestamp, Valid: deletedTimestamp > 0},
		VmId:           sql.NullString{String: event.CloudEvent.Data.VM.VM.Value, Valid: event.CloudEvent.Data.VM.VM.Value != ""},
		DatacenterName: sql.NullString{String: event.CloudEvent.Data.Datacenter.Name, Valid: event.CloudEvent.Data.Datacenter.Name != ""},
	}
	h.Logger.Debug("database params", "params", params)
	err = h.Database.Queries().InventoryMarkDeleted(context.Background(), params)

	if err != nil {
		h.Logger.Error("Error received marking VM as deleted", "error", err)
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Delete Request unsuccessful %s\n", err)
	} else {
		h.Logger.Debug("Processed VM Deletion event successfully")
		w.WriteHeader(http.StatusOK)
		// TODO - return some JSON
		fmt.Fprintf(w, "Processed VM Deletion event successfully")
	}

	//h.Logger.Debug("received delete request", "body", string(reqBody))
	//w.WriteHeader(http.StatusOK)
	//fmt.Fprintf(w, "Delete Request (%d): %v\n", len(reqBody), string(reqBody))
}
