package controllers

import (
	"database/sql"
	"errors"
	"net/http"
	"officeHours/templating"
)

// Check the secret token for requests and execute the request for correct tokens
func (b *BaseHandler) ConfirmRequestHandler(w http.ResponseWriter, req *http.Request) {
	SendSecurityHeaders(w, req)
	secret := req.FormValue("code")
	request, err := b.requestRepo.FindBySecret(secret)

	if errors.Is(err, sql.ErrNoRows) { // There was no request with this secret
		w.WriteHeader(http.StatusNotFound)
		templating.ServeTemplate(w, "requestNotFound", nil)
		return
	}
	if err != nil { // Some other error happened finding the request with this secret
		w.WriteHeader(http.StatusInternalServerError)
		templating.ServeTemplate(w, "executeFailure", err.Error())
		return
	}

	err = b.requestRepo.Execute(request)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		templating.ServeTemplate(w, "executeFailure", err.Error())
		return
	}
	templating.ServeTemplate(w, "executeSuccess", nil)
}
