package media

import (
	"context"
	"log"
	"net/http"
	"os"

	"fr.latosa-escrima/core"
	"fr.latosa-escrima/core/models"
)

func HandleDelete(w http.ResponseWriter, r *http.Request) {
	uuid := r.PathValue("media_uuid")
	var media models.Media
	res, err := core.DB.NewDelete().
		Model(&media).
		Where("id = ?", uuid).
		Returning("*").
		Exec(context.Background())
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}
	log.Println(res)
	err = os.Remove(media.Path)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	core.JSONSuccess{
		Status:  core.Success,
		Message: "Image successfully deleted.",
	}.Respond(w, http.StatusOK)
}
