package main

import (
	"golang-csv/config"
	"golang-csv/cron"
	"golang-csv/cron_mst"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

var cronFunctions = map[string]func() error{
	"/processCSVPo":               cron.ProcessCSVPo,
	"/processCSVSo":               cron.ProcessCSVSo,
	"/processCSVIn":               cron.ProcessAndInsertDataIn,
	"/processCSVOut":              cron.ProcessAndInsertDataOut,
	"/processCSVMstItem":          cron_mst.ProcessCSVItem,
	"/processCSVMstCostumer":      cron_mst.ProcessCSVCust,
	"/processCSVSupplier":         cron_mst.ProcessCSVSupp,
	"/insertDataFromCSV":          cron.InsertDataFromCSV,
	"/processAndInsertDataOpname": cron.ProcessAndInsertDataOpname,
	"/processAndInsertWIPIn":      cron.ProcessAndInsertWIPIn,
	"/processAndInsertWIPOut":     cron.ProcessAndInsertWIPOut,
	"/processAndInsertFGOut":      cron.ProcessAndInsertFGOut,
	"/processAndInsertFGIn":       cron.ProcessAndInsertFGIn,
	"/processAndInsertME":         cron.ProcessAndInsertME,
}

func handleCronRequest(w http.ResponseWriter, r *http.Request) {

	cronFunc, exists := cronFunctions[r.URL.Path]
	if !exists {
		http.Error(w, "Unknown cron function", http.StatusNotFound)
		return
	}

	err := cronFunc()
	if err != nil {
		log.Printf("Error processing %s: %v", r.URL.Path, err)
		http.Error(w, "Failed to process cron job", http.StatusInternalServerError)
		return
	}

	//w.Write([]byte("Cron job processed successfully"))
}

func main() {
	log.Println("Starting the application...")

	// Load configuration
	cfg := config.LoadConfig()

	log.Printf("Loaded config: %+v\n", cfg)

	for path := range cronFunctions {
		http.HandleFunc(path, handleCronRequest)
	}

	// Start the HTTPS server in a separate goroutine
	go func() {
		log.Println("Starting HTTPS server on port 8080...")
		// for server
		// if err := http.ListenAndServeTLS(":8080", "corinthian_app.crt", "corinthian_app.key", nil); err != nil {
		// 	log.Fatalf("Failed to start HTTPS server: %v", err)
		// }

		//for development
		if err := http.ListenAndServe(":8080", nil); err != nil {
			log.Fatalf("Failed to start HTTP server: %v", err)
		}
	}()

	// Handle graceful shutdown
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

	log.Println("Press Ctrl+C to stop.")
	<-sigs

	log.Println("Shutting down gracefully...")
}
