/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package form

import (
	"io"
	"net/http"

	"dev.tandem.ws/tandem/camper/pkg/auth"
	httplib "dev.tandem.ws/tandem/camper/pkg/http"
	"dev.tandem.ws/tandem/camper/pkg/locale"
)

func HandleMultipart(f MultipartForm, w http.ResponseWriter, r *http.Request, user *auth.User) (bool, error) {
	if err := f.ParseMultipart(w, r); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return false, err
	}
	if err := user.VerifyCSRFToken(r); err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		_ = f.Close()
		return false, err
	}
	if !f.Valid(user.Locale) {
		if !httplib.IsHTMxRequest(r) {
			w.WriteHeader(http.StatusUnprocessableEntity)
		}
		_ = f.Close()
		return false, nil
	}
	return true, nil
}

type MultipartForm interface {
	io.Closer
	ParseMultipart(w http.ResponseWriter, r *http.Request) error
	Valid(l *locale.Locale) bool
}

func Handle(f Form, w http.ResponseWriter, r *http.Request, user *auth.User) (bool, error) {
	if err := f.Parse(r); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return false, err
	}
	if err := user.VerifyCSRFToken(r); err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return false, err
	}
	if !f.Valid(user.Locale) {
		if !httplib.IsHTMxRequest(r) {
			w.WriteHeader(http.StatusUnprocessableEntity)
		}
		return false, nil
	}
	return true, nil
}

type Form interface {
	Parse(r *http.Request) error
	Valid(l *locale.Locale) bool
}
