package service

import (
	"Portifolio/internal/database"
	"Portifolio/internal/model"
	"database/sql"
	"fmt"

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

func UpdatePositionByTradeList(db *sql.DB) error {

	trades, err := database.GetTrades(db)
	if err != nil {
		fmt.Printf("Failed to get the trades from db: %s", err)
	}

	TradeSum := make(map[string]model.Position)

	for _, trade := range trades {
		if trade.Type == model.Buy {
			TradeSum[trade.Symbol] = model.Position{
				Symbol:       trade.Symbol,
				CurrencyCode: trade.CurrencyCode,
				CostBasis:    TradeSum[trade.Symbol].CostBasis + trade.Price,
				Shares:       TradeSum[trade.Symbol].Shares + trade.Shares,
			}
		} else {
			TradeSum[trade.Symbol] = model.Position{
				Symbol:       trade.Symbol,
				CurrencyCode: trade.CurrencyCode,
				CostBasis:    TradeSum[trade.Symbol].CostBasis - trade.Price,
				Shares:       TradeSum[trade.Symbol].Shares - trade.Shares,
			}
		}

	}

	var NewPositinos []model.Position
	for _, pos := range TradeSum {
		NewPositinos = append(NewPositinos, pos)
	}

	err = database.UpdatePositions(db, NewPositinos)
	if err != nil {
		return fmt.Errorf("Failed to insert the new postions number into db: %s", err)
	}

	return nil
}
