package handlers

import (
	"Portifolio/internal/database"
	"Portifolio/internal/model"
	"Portifolio/internal/service"
	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"

	_ "github.com/mattn/go-sqlite3"
)

func AddTradeHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req model.AddTradeRequest
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, "invalid json", http.StatusBadRequest)
			return
		}

		err := req.Validate()
		if err != nil {
			http.Error(w, fmt.Sprintf("failed to validate trade: %s", err), http.StatusInternalServerError)
			return
		}

		// check if currency is in the db.
		currency, err := database.GetCurrencyByCode(db, req.CurrencyCode)
		if err != nil {
			http.Error(w, fmt.Sprintf("failed to find currency: %s", err), http.StatusInternalServerError)
			return
		}

		trade := model.Trade{
			Symbol:       req.Symbol,
			Shares:       req.Shares,
			Product:      model.TradeProduct(req.Product),
			Type:         model.TradeType(req.Type),
			Price:        req.Price,
			CurrencyCode: currency.Code,
			Date:         req.Date,
		}

		err = database.InsertTrade(db, trade)
		if err != nil {
			http.Error(w, fmt.Sprintf("failed to insert trade into db: %s", err), http.StatusInternalServerError)
			return
		}

		err = service.UpdatePositionByTradeList(db)
		update := true
		if err != nil {
			update = false
		}

		w.Header().Set("Content-Type", "application/json")
		if err := json.NewEncoder(w).Encode(map[string]any{"success": true, "position update": update}); err != nil {
			http.Error(w, fmt.Sprintf("failed to encode trades: %s", err), http.StatusInternalServerError)
			return
		}
	}
}

func GetTradeListHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		tradeList, err := database.GetTrades(db)
		if err != nil {
			http.Error(w, fmt.Sprintf("failed to fetch trades: %s", err), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		if err := json.NewEncoder(w).Encode(tradeList); err != nil {
			http.Error(w, fmt.Sprintf("failed to encode trades: %s", err), http.StatusInternalServerError)
			return
		}
	}
}

func GetPositionListHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		posList, err := database.GetPositions(db)
		if err != nil {
			http.Error(w, fmt.Sprintf("failed to fetch postiton: %s", err), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		if err := json.NewEncoder(w).Encode(map[string]any{"List": posList}); err != nil {
			http.Error(w, fmt.Sprintf("failed to encode positions: %s", err), http.StatusInternalServerError)
			return
		}
	}
}
