package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/gorilla/mux"
	"github.com/jinzhu/gorm"
	"github.com/rs/cors"
)

var (
	db     *gorm.DB // Declare db globally
	config *Config
)

func main() {

	configFile := os.Getenv("CONFIG")
	var err error
	config, err = LoadConfig(configFile)

	// check for errors
	if err != nil || config == nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	fmt.Println(config.DatabasePath)
	fmt.Println(config.ImageStorageDir)
	fmt.Println(config.JWTSecret)
	fmt.Println(config.LogFile)
	fmt.Println(config.ListeningPort)

	// Connect to the database
	db, err = ConnectDB(config.DatabasePath)
	if err != nil || db == nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}
	defer db.Close()

	fmt.Println("Default user 'boxuser' created successfully!")

	// Create the router
	router := mux.NewRouter()

	// Define your routes
	router.Handle("/login", http.HandlerFunc(LoginHandler)).Methods("POST", "OPTIONS")
	router.Handle("/boxes", AuthMiddleware(http.HandlerFunc(GetBoxesHandler))).Methods("GET", "OPTIONS")
	router.Handle("/boxes", AuthMiddleware(http.HandlerFunc(CreateBoxHandler))).Methods("POST", "OPTIONS")
	router.Handle("/boxes/{id}", AuthMiddleware(http.HandlerFunc(DeleteBoxHandler))).Methods("DELETE", "OPTIONS")
	router.Handle("/boxes/{id}", AuthMiddleware(http.HandlerFunc(GetBoxHandler))).Methods("GET", "OPTIONS")
	router.Handle("/items", AuthMiddleware(http.HandlerFunc(GetItemsHandler))).Methods("GET", "OPTIONS")
	router.Handle("/items", AuthMiddleware(http.HandlerFunc(CreateItemHandler))).Methods("POST", "OPTIONS")
	router.Handle("/items/{id}", AuthMiddleware(http.HandlerFunc(GetItemHandler))).Methods("GET", "OPTIONS")
	router.Handle("/boxes/{id}/items", AuthMiddleware(http.HandlerFunc(GetItemsInBoxHandler))).Methods("GET", "OPTIONS")
	router.Handle("/items/{id}", AuthMiddleware(http.HandlerFunc(UpdateItemHandler))).Methods("PUT", "OPTIONS")
	router.Handle("/items/{id}", AuthMiddleware(http.HandlerFunc(DeleteItemHandler))).Methods("DELETE", "OPTIONS")
	router.Handle("/items/{id}/image", AuthMiddleware(http.HandlerFunc(GetItemImageHandler))).Methods("GET", "OPTIONS")
	fmt.Println("Registering route for search items...")
	router.Handle("/search/items", AuthMiddleware(http.HandlerFunc(SearchItemsHandler))).Methods("GET", "OPTIONS")
	// Add a new route for uploading an image with AuthMiddleware
	router.HandleFunc("/items/{id}/upload", UploadItemImageHandler).
		Methods("POST").
		Handler(AuthMiddleware(http.HandlerFunc(UploadItemImageHandler)))

	// Apply CORS middleware
	c := cors.New(cors.Options{
		AllowedOrigins:   []string{"http://localhost:3000", "http://10.0.0.16:3000"}, // Change this to your frontend domain
		AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowedHeaders:   []string{"Authorization", "Content-Type"},
		AllowCredentials: true,
	})

	// Start the server with CORS middleware
	fmt.Printf("Server listening on port %d\n", config.ListeningPort)
	http.ListenAndServe(fmt.Sprintf(":%d", config.ListeningPort), c.Handler(router))
}
