package handler

import (
	"encoding/json"
	"fmt"
	"net/http"
	"portfolio-tracker/internal/model"
	"portfolio-tracker/internal/session"
	"portfolio-tracker/internal/util"
	"portfolio-tracker/internal/web/templates"

	"github.com/a-h/templ"
)

// Helper function to get session info
func getSessionInfo(r *http.Request) (bool, string, error) {
	session, err := session.Store.Get(r, "hnrx_pft_session")
	if err != nil {
		return false, "", err
	}

	auth, ok := session.Values["authenticated"].(bool)
	if !ok {
		auth = false
	}

	username, ok := session.Values["username"].(string)
	if !ok {
		username = ""
	}

	return auth, username, nil
}

// Helper function to get portfolios for a user
func getUserPortfolios(username string) []model.Portfolio {
	var portfolios []model.Portfolio
	if username != "" {
		// Get user first
		var user model.User
		if err := DB.Where("username = ?", username).First(&user).Error; err != nil {
			fmt.Printf("Error getting user: %v\n", err)
			return portfolios
		}

		// Get user's portfolios
		if err := DB.Where("user_id = ?", user.ID).Find(&portfolios).Error; err != nil {
			fmt.Printf("Error getting portfolios: %v\n", err)
		}
	}
	return portfolios
}

func Handler(w http.ResponseWriter, r *http.Request) {
	auth, username, err := getSessionInfo(r)
	if err != nil {
		fmt.Printf("Session error: %v\n", err)
	}

	portfolios := getUserPortfolios(username)

	// Debug output
	fmt.Printf("Session values - Auth: %v, Username: %s\n", auth, username)

	component := templates.Result(auth, username, portfolios)
	templ.Handler(component).ServeHTTP(w, r)
}

func DetailsHandler(w http.ResponseWriter, r *http.Request) {
	auth, username, err := getSessionInfo(r)
	if err != nil {
		fmt.Printf("Session error in DetailsHandler: %v\n", err)
	}

	portfolios := getUserPortfolios(username)

	stock := r.URL.Query().Get("stock")
	if stock == "" {
		http.Error(w, "Fehlender stock-Parameter", http.StatusBadRequest)
		return
	}

	data, err := util.FetchYahooFinanceData(stock)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	var resp model.YahooChartResponse
	err = json.Unmarshal([]byte(data), &resp)
	if err != nil {
		http.Error(w, "Fehler beim Parsen der Daten: "+err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	templates.StockDetails(auth, username, stock, resp, portfolios).Render(r.Context(), w)
}
