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

package app

import (
	"errors"
	"net/http"

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

type loginForm struct {
	Email    *form.Input
	Password *form.Input
	Redirect *form.Input
	Error    error
}

func newLoginForm() *loginForm {
	return &loginForm{
		Email: &form.Input{
			Name: "email",
		},
		Password: &form.Input{
			Name: "password",
		},
		Redirect: &form.Input{
			Name: "redirect",
		},
	}
}

func (f *loginForm) Parse(r *http.Request) error {
	if err := r.ParseForm(); err != nil {
		return err
	}
	f.Email.FillValue(r)
	f.Password.FillValue(r)
	f.Redirect.FillValue(r)
	if f.Redirect.Val == "" {
		f.Redirect.Val = "/admin/"
	}
	return nil
}

func (f *loginForm) Valid(l *locale.Locale) bool {
	v := form.NewValidator(l)
	if v.CheckRequired(f.Email, l.GettextNoop("Email can not be empty.")) {
		v.CheckValidEmail(f.Email, l.GettextNoop("This email is not valid. It should be like name@domain.com."))
	}
	v.CheckRequired(f.Password, l.GettextNoop("Password can not be empty."))
	return v.AllOK
}

func (f *loginForm) MustRender(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company) {
	template.MustRenderAdmin(w, r, user, company, "login.gohtml", f)
}

func serveLoginForm(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, redirectPath string) {
	login := newLoginForm()
	login.Redirect.Val = redirectPath
	login.MustRender(w, r, user, company)
}

func handleLogin(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
	login := newLoginForm()
	if err := login.Parse(r); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if login.Valid(user.Locale) {
		cookie := conn.MustGetText(r.Context(), "select login($1, $2, $3)", login.Email, login.Password, httplib.RemoteAddr(r))
		if cookie != "" {
			auth.SetSessionCookie(w, cookie)
			httplib.Redirect(w, r, login.Redirect.Val, http.StatusSeeOther)
			return
		}
		login.Error = errors.New(user.Locale.Gettext("Invalid user or password."))
		w.WriteHeader(http.StatusUnauthorized)
	} else {
		w.WriteHeader(http.StatusUnprocessableEntity)
	}
	login.MustRender(w, r, user, company)
}

func handleLogout(w http.ResponseWriter, r *http.Request, user *auth.User, conn *database.Conn) {
	if err := user.VerifyCSRFToken(r); err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}
	conn.MustExec(r.Context(), "select logout()")
	auth.DeleteSessionCookie(w)
	httplib.Redirect(w, r, "/login", http.StatusSeeOther)
}
