package routes

import (
	"gifuu/tools"
	"net/http"
)

func POST_Art_ID_Reports(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	var Body struct {
		ReasonType int    `json:"type"`
		ReasonText string `json:"reason"`
	}

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

	if err := tools.ParseJSON(r.Body, &Body); err != nil {
		tools.SendClientError(w, r, tools.ERROR_BODY_INVALID_DATA)
		return
	}

	if Body.ReasonType < REPORT_REASON_EXPLICIT || Body.ReasonType > REPORT_REASON_ILLEGAL {
		tools.SendClientError(w, r, tools.ERROR_BODY_INVALID_FIELD)
		return
	}

	if str, ok := tools.NormalizeComment(Body.ReasonText); !ok {
		tools.SendClientError(w, r, tools.ERROR_BODY_INVALID_FIELD)
		return
	} else {
		Body.ReasonText = str
	}

	// Attempt to store the users report. It may be discarded if another moderator
	// has previously review this item and deemed it didn't violate any rules.

	if _, err := tools.Database.Exec(ctx,
		`INSERT INTO gifuu.mod_report (upload_id, reason_type, reason_text, report_address_hash)
		SELECT $1, $2, $3, $4 FROM gifuu.upload WHERE id = $1 AND flag_bypass = FALSE`,
		paramID,
		Body.ReasonType,
		Body.ReasonText,
		tools.RequestAddressHash(r),
	); err != nil {
		tools.SendServerError(w, r, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
