package server

import (
	"local/oauth2"
	"local/storage"
	"net/http"

	"github.com/google/uuid"
)

func (s *Server) authorize(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.NotFound(w, r)
		return
	}
	id := r.FormValue("username")
	user, ok := s.getUser(id)
	if !ok {
		http.Error(w, "unknown user", http.StatusForbidden)
		return
	}
	access, ok := s.getAccess(user)
	if !ok {
		http.Error(w, "no oauth for user", http.StatusForbidden)
		return
	}
	cookie := &http.Cookie{
		Name:     oauth2.COOKIE,
		Value:    access,
		SameSite: http.SameSiteLaxMode,
	}
	http.SetCookie(w, cookie)
	redirectCookie, err := r.Cookie(oauth2.REDIRECT)
	if err != nil {
		return
	}
	http.Redirect(w, r, redirectCookie.Value, http.StatusSeeOther)
}

func (s *Server) genAuth(user string) {
	access := uuid.New().String()
	token := uuid.New().String()
	s.store.Set(user, []byte(access), ACCESS)
	s.store.Set(access, []byte(token), TOKEN)
}

func (s *Server) getAccess(user string) (string, bool) {
	access, err := s.store.Get(user, ACCESS)
	if err == storage.ErrNotFound {
		s.genAuth(user)
		access, err = s.store.Get(user, ACCESS)
	}
	return string(access), err == nil
}

func (s *Server) getToken(access string) (string, bool) {
	token, err := s.store.Get(access, TOKEN)
	return string(token), err == nil
}
