package main

import (
	"Portifolio/internal/database"
	"Portifolio/internal/handlers"
	"Portifolio/internal/shell"
	"bufio"
	"database/sql"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"

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

var db *sql.DB

func main() {
	var err error
	db, err = sql.Open("sqlite3", "./app.db?_foreign_keys=on")
	if err != nil {
		log.Fatal("Failed to open database:", err)
	}
	defer db.Close()

	if err = db.Ping(); err != nil {
		log.Fatal("Failed to connect to database:", err)
	}

	database.InitDB(db)
	database.MigrateAddUniqueToRevenueEntries(db)
	fmt.Println("Connected to SQLite database")

	http.HandleFunc("/health", handlers.HealthHandler(db))

	//Trades
	http.HandleFunc("POST /trade/add", handlers.AddTradeHandler(db))
	http.HandleFunc("GET /trade/list", handlers.GetTradeListHandler(db))
	http.HandleFunc("GET /positions/list", handlers.GetTradeListHandler(db))

	// Company
	http.HandleFunc("POST /company/add", handlers.AddCompanyHandler(db))
	http.HandleFunc("GET /company/list", handlers.GetCompaniesHandler(db))
	http.HandleFunc("GET /company/revenue/categories", handlers.GetCompanyRevenueCategories(db))

	// Currency
	http.HandleFunc("GET /currencies", handlers.GetCurrenciesHandler(db))

	// Revenue
	http.HandleFunc("POST /add/revenue/entry", handlers.AddRevenueEntryHandler(db))
	http.HandleFunc("POST /api/v1/revenue/add", handlers.AddRevenueEntryHandler(db))

	//http.HandleFunc("GET /revenue/report", handlers.GetRevenueReportHandler(db))

	fmt.Println("Server running on :8080")
	go func() {
		log.Fatal(http.ListenAndServe(":8080", nil))
	}()

	runShell(db)
}

func runShell(db *sql.DB) {
	scanner := bufio.NewScanner(os.Stdin)
	fmt.Println("\nShell ready. Type 'help' for commands.")

	for {
		fmt.Print("> ")
		if !scanner.Scan() {
			break
		}

		parts := strings.Fields(scanner.Text())
		if len(parts) == 0 {
			continue
		}

		switch parts[0] {
		// Company
		case "add-company":
			shell.AddCompany(scanner, db)
		case "list-companies":
			shell.ListCompanies(db)

		// Currency
		case "add-currency":
			shell.AddCurrency(scanner, db)
		case "list-currency":
			shell.ListCurrencies(db)

		// Revenue
		case "add-revenue":
			shell.AddRevenue(scanner, db)
		case "list-revenue":
			shell.ListRevenue(scanner, db)

		case "help":
			fmt.Println("\nCommands:")
			fmt.Println("  --- Company ---")
			fmt.Println("  add-company       add a new company")
			fmt.Println("  list-companies    list all companies")
			fmt.Println("  --- Currency ---")
			fmt.Println("  add-currency      add a new currency")
			fmt.Println("  list-currency     list all currencies")
			fmt.Println("  --- Revenue ---")
			fmt.Println("  add-revenue       add a revenue entry interactively")
			fmt.Println("  list-revenue      list revenue for a company/period")
			fmt.Println("  sum-revenue       sum revenue across periods")
			fmt.Println("  --- Other ---")
			fmt.Println("  exit              quit")

		case "exit":
			fmt.Println("Bye!")
			os.Exit(0)

		default:
			fmt.Printf("Unknown command: %s. Type 'help' for commands.\n", parts[0])
		}
	}
}
