package routes

import (
	"gifuu/tools"
	"net/http"
	"os"
	"path"
	"strconv"
)

func DELETE_Art_ID(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	query := r.URL.Query()

	paramToken := query.Get("token")
	paramID := tools.ParseSnowflake(r.PathValue("id"))
	if paramToken == "" || paramID == 0 {
		tools.SendClientError(w, r, tools.ERROR_BODY_INVALID_FIELD)
		return
	}

	// Delete Art
	tag, err := tools.Database.Exec(ctx,
		`DELETE FROM gifuu.upload WHERE id = $1 AND upload_token_hash = $2`,
		paramID,
		tools.RequestHash(paramToken),
	)
	if err != nil {
		tools.SendServerError(w, r, err)
		return
	}
	if tag.RowsAffected() == 0 {
		tools.SendClientError(w, r, tools.ERROR_GENERIC_UNAUTHORIZED)
		return
	}

	go RemoveFilesForArt(paramID)

	w.WriteHeader(http.StatusNoContent)
}

func RemoveFilesForArt(artID int64) {
	normal := strconv.FormatInt(artID, 10)
	target := path.Join(tools.STORAGE_DISK_PUBLIC, normal)
	if err := os.RemoveAll(target); err != nil {
		tools.LoggerStorage.Log(tools.WARN, "Failed to delete directory '%s': %s", target, err)
	}
}
