package Api

import (
	"log"
	"net/http"

	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Api/Auth"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Api/Friends"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Api/Messages"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Api/Users"

	"github.com/gorilla/mux"
)

func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Printf(
			"%s %s, Content Length: %d",
			r.Method,
			r.RequestURI,
			r.ContentLength,
		)

		next.ServeHTTP(w, r)
	})
}

func authenticationMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var err error

		_, err = Auth.CheckCookie(r)
		if err != nil {
			http.Error(w, "Forbidden", http.StatusUnauthorized)
			return
		}

		next.ServeHTTP(w, r)
	})
}

// InitAPIEndpoints initializes all API endpoints required by mobile app
func InitAPIEndpoints(router *mux.Router) {
	var (
		api     *mux.Router
		authAPI *mux.Router
		fs      http.Handler
	)

	log.Println("Initializing API routes...")

	api = router.PathPrefix("/api/v1/").Subrouter()
	api.Use(loggingMiddleware)

	// Define routes for authentication
	api.HandleFunc("/signup", Auth.Signup).Methods("POST")
	api.HandleFunc("/login", Auth.Login).Methods("POST")
	api.HandleFunc("/logout", Auth.Logout).Methods("GET")

	authAPI = api.PathPrefix("/auth/").Subrouter()
	authAPI.Use(authenticationMiddleware)

	authAPI.HandleFunc("/check", Auth.Check).Methods("GET")

	authAPI.HandleFunc("/change_password", Auth.ChangePassword).Methods("POST")
	authAPI.HandleFunc("/message_expiry", Auth.ChangeUserMessageExpiry).Methods("POST")
	authAPI.HandleFunc("/image", Auth.AddProfileImage).Methods("POST")

	authAPI.HandleFunc("/users", Users.SearchUsers).Methods("GET")

	authAPI.HandleFunc("/friend_requests", Friends.FriendRequestList).Methods("GET")
	authAPI.HandleFunc("/friend_request", Friends.CreateFriendRequest).Methods("POST")
	authAPI.HandleFunc("/friend_request/qr_code", Friends.CreateFriendRequestQrCode).Methods("POST")
	authAPI.HandleFunc("/friend_request/{requestID}", Friends.AcceptFriendRequest).Methods("POST")
	authAPI.HandleFunc("/friend_request/{requestID}", Friends.RejectFriendRequest).Methods("DELETE")

	authAPI.HandleFunc("/conversations", Messages.ConversationList).Methods("GET")
	authAPI.HandleFunc("/conversation_details", Messages.ConversationDetailsList).Methods("GET")
	authAPI.HandleFunc("/conversations", Messages.CreateConversation).Methods("POST")
	authAPI.HandleFunc("/conversations", Messages.UpdateConversation).Methods("PUT")
	authAPI.HandleFunc("/conversations/{detailID}/image", Messages.AddConversationImage).Methods("POST")
	authAPI.HandleFunc("/conversations/{detailID}/message_expiry", Messages.ChangeConversationMessageExpiry).Methods("POST")

	authAPI.HandleFunc("/message", Messages.CreateMessage).Methods("POST")
	authAPI.HandleFunc("/messages/{associationKey}", Messages.Messages).Methods("GET")

	// TODO: Add authentication to this route
	fs = http.FileServer(http.Dir("./attachments/"))
	router.PathPrefix("/files/").Handler(http.StripPrefix("/files/", fs))
}
