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
		}

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

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

		switch model.TradeType(req.Type) {
		case model.DividendType:
			dividend, err := req.ToDividend()
			if err != nil {
				http.Error(w, fmt.Sprintf("failed to build dividend: %s", err), http.StatusBadRequest)
				return
			}
			dividend.CurrencyCode = currency.Code

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

			w.Header().Set("Content-Type", "application/json")
			json.NewEncoder(w).Encode(map[string]any{"success": true})

		case model.BuyType, model.SellType:
			trade, err := req.ToTrade()
			if err != nil {
				http.Error(w, fmt.Sprintf("failed to build trade: %s", err), http.StatusBadRequest)
				return
			}
			trade.CurrencyCode = currency.Code

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

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

			w.Header().Set("Content-Type", "application/json")
			json.NewEncoder(w).Encode(map[string]any{"success": true, "position_update": update})

		default:
			http.Error(w, fmt.Sprintf("unknown trade type: %d", req.Type), http.StatusBadRequest)
		}
	}
}

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(posList); err != nil {
			http.Error(w, fmt.Sprintf("failed to encode positions: %s", err), http.StatusInternalServerError)
			return
		}
	}
}
