package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"legalgo-BE-go/config"
	"legalgo-BE-go/database"
	repository "legalgo-BE-go/internal/accessor"
	internalhttp "legalgo-BE-go/internal/api/http"
	pkgconfig "legalgo-BE-go/internal/config"
	"legalgo-BE-go/internal/services"

	"github.com/go-chi/chi/v5"
	"github.com/joho/godotenv"
	"github.com/redis/go-redis/v9"
	"go.uber.org/fx"
)

func init() {
	// Check if the .env file exists
	if _, err := os.Stat(".env"); err == nil {
		// Load environment variables from .env file if it exists
		if err := godotenv.Load(); err != nil {
			log.Println("Error loading .env file, continuing without it")
		}
	} else {
		log.Println(".env file not found, skipping load")
	}

	config.InitEnv()
}

func run(
	lc fx.Lifecycle,
	db *database.DB,
	apiRouter chi.Router,
	rdb *redis.Client,
) {
	lc.Append(fx.Hook{
		OnStart: func(ctx context.Context) error {
			fmt.Println("Application has started...")
			_, err := rdb.Ping(ctx).Result()
			if err != nil {
				log.Fatalf("Could not connect to Redis: %v", err)
			}
			pkgconfig.Router(apiRouter)

			return nil
		},
		OnStop: func(ctx context.Context) error {
			fmt.Println("Shutting down...")
			rdb.Close()
			return nil
		},
	})
}

func main() {
	app := fx.New(
		config.Module,
		database.Module,
		repository.Module,
		services.Module,
		internalhttp.Module,
		fx.Invoke(run),
	)

	if err := app.Start(context.Background()); err != nil {
		log.Fatal("Error starting app:", err)
	}

	// Wait for the app to stop gracefully
	if err := app.Stop(context.Background()); err != nil {
		log.Fatal("Error stopping app:", err)
	}
}
