package main

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

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"github.com/zs/InsightReply/internal/handler"
	"github.com/zs/InsightReply/internal/repository"
	"github.com/zs/InsightReply/internal/service"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

func main() {
	// Database connection (Using the provided string)
	dsn := "postgres://root:QG%237X*HHt3CqbZ@100.64.0.5:5432/InsightReply?sslmode=disable"
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("failed to connect database:", err)
	}

	fmt.Println("Database connection established")

	// Initialize Layers
	userRepo := repository.NewUserRepository(db)
	userSvc := service.NewUserService(userRepo)
	userHandler := handler.NewUserHandler(userSvc)

	// AI Service (Using Env Var for API Key)
	apiKey := os.Getenv("OPENAI_API_KEY")
	aiSvc := service.NewAIService(apiKey)
	aiHandler := handler.NewAIHandler(aiSvc)

	// Router setup
	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)

	r.Route("/api/v1", func(r chi.Router) {
		r.Post("/users/register", userHandler.Register)
		r.Get("/ai/test", aiHandler.Test)
		r.Post("/ai/generate", aiHandler.Generate)
	})

	fmt.Println("Server starting on :8080")
	if err := http.ListenAndServe(":8080", r); err != nil {
		log.Fatal(err)
	}
}
