package database

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

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

func GetTrades(db *sql.DB) ([]model.Trade, error) {
	rows, err := db.Query("SELECT company_id, currency_id, shares, product, type, price, traded_at FROM trades")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var trades []model.Trade

	for rows.Next() {
		var TickerInt int
		var CurrencyInt int
		var TypeInt int

		var t model.Trade
		err := rows.Scan(&TickerInt, &CurrencyInt, &t.Shares, &t.Product, &TypeInt, &t.Price, &t.Date)
		if err != nil {
			return nil, err
		}

		company, err := GetCompanyByID(db, TickerInt)
		if err != nil {
			return nil, err
		}
		currency, err := GetCurrencyByID(db, CurrencyInt)
		if err != nil {
			return nil, err
		}
		t.Currency = currency.Name
		t.Ticker = *company
		switch TypeInt {
		case 0:
			t.Type = model.TradeType(false)
		case 1:
			t.Type = model.TradeType(true)
		default:
			return nil, fmt.Errorf("failed to convert given Type int to bool of trade type.")
		}

		trades = append(trades, t)
	}
	if err = rows.Err(); err != nil {
		return nil, err
	}

	return trades, nil
}

func GetPositions(db *sql.DB) ([]model.Position, error) {
	rows, err := db.Query("SELECT company_id, shares, weight, CostBases, currency_id")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var positions []model.Position
	for rows.Next() {
		var t model.Position
		err := rows.Scan(&t.Company.ID, &t.Shares, &t.Weight, &t.CostBasis, t.Currency)
		if err != nil {
			return nil, err
		}
		positions = append(positions, t)
	}
	if err = rows.Err(); err != nil {
		return nil, err
	}

	return positions, nil
}

func InsertTrade(db *sql.DB, trade model.Trade) error {
	_, err := db.Exec(
		"INSERT INTO trades (company_id, currency_id, shares, product, type, price, traded_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
		trade.Ticker.ID,
		trade.Currency,
		trade.Shares,
		trade.Product,
		trade.Type,
		trade.Price,
		trade.Date,
	)
	return err
}
