package main

import (
	"fmt"
	"github.com/google/uuid"
	"go-nkode/core/api"
	"go-nkode/core/model"
	"go-nkode/core/nkode"
	"log"
	"net/http"
)

func main() {
	//db := nkode.NewInMemoryDb()
	db, err := nkode.NewSqliteDB("nkode.db")
	if err != nil {
		log.Fatal(err)
	}
	nkodeApi := nkode.NewNKodeAPI(db)
	AddDefaultCustomer(nkodeApi)
	handler := model.NKodeHandler{Api: &nkodeApi}
	mux := http.NewServeMux()
	mux.Handle(api.CreateNewCustomer, &handler)
	mux.Handle(api.GenerateSignupInterface, &handler)
	mux.Handle(api.SetNKode, &handler)
	mux.Handle(api.ConfirmNKode, &handler)
	mux.Handle(api.GetLoginInterface, &handler)
	mux.Handle(api.Login, &handler)
	mux.Handle(api.RenewAttributes, &handler)
	fmt.Println("Running on localhost:8080...")
	log.Fatal(http.ListenAndServe("localhost:8080", corsMiddleware(mux)))
}

func corsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Set the CORS headers
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		// Handle preflight requests
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusNoContent)
			return
		}

		// Call the next handler
		next.ServeHTTP(w, r)
	})
}

func AddDefaultCustomer(api nkode.NKodeAPI) {
	newId, err := uuid.Parse("ed9ed6e0-082c-4b57-8d8c-f00ed6493457")
	if err != nil {
		log.Fatal(err)
	}
	customerId := model.CustomerId(newId)
	nkode_policy := model.NewDefaultNKodePolicy()
	_, err = api.CreateNewCustomer(nkode_policy, &customerId)
	if err != nil {
		log.Print(err)
	} else {
		log.Print("created new customer: ", newId)
	}
}
