package shell

import (
	"Portifolio/internal/database"
	"Portifolio/internal/model"
	"Portifolio/internal/service"
	"bufio"
	"database/sql"
	"fmt"
	"strconv"
	"strings"

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

func AddCompany(scanner *bufio.Scanner, db *sql.DB) {
	input := model.CompanyInput{}

	fmt.Print("  Name: ")
	scanner.Scan()
	input.Name = strings.TrimSpace(scanner.Text())

	fmt.Print("  Shares outstanding: ")
	scanner.Scan()
	shares, err := strconv.Atoi(strings.TrimSpace(scanner.Text()))
	if err != nil {
		fmt.Println("  Invalid number for shares.")
		return
	}
	input.SharesOutstanding = shares

	fmt.Print("  Price: ")
	scanner.Scan()
	price, err := strconv.ParseFloat(strings.TrimSpace(scanner.Text()), 64)
	if err != nil {
		fmt.Println("  Invalid number for price.")
		return
	}
	input.Price = price

	fmt.Print("  Currency ID: ")
	scanner.Scan()
	cid, err := strconv.Atoi(strings.TrimSpace(scanner.Text()))
	if err != nil {
		fmt.Println("  Invalid currency ID.")
		return
	}
	input.CurrencyID = cid

	if err := service.AddCompany(input, db); err != nil {
		fmt.Println("  Error:", err)
		return
	}
	fmt.Printf("  ✓ Company '%s' added.\n", input.Name)
}

func ListCompanies(db *sql.DB) {
	companies, err := service.GetAllCompanies(db)
	if err != nil {
		fmt.Println("  ✗ Error:", err)
		return
	}

	if len(companies) == 0 {
		fmt.Println("  No companies found.")
		return
	}

	fmt.Printf("\n  %-5s %-20s %-10s %-15s %s\n", "ID", "NAME", "CURRENCY", "PRICE", "SHARES")
	fmt.Println("  " + strings.Repeat("-", 60))
	for _, c := range companies {

		currency, err := database.GetCurrencyByID(db, c.CurrencyID)
		if err != nil {
			fmt.Println("No currency by id.")
			return
		}

		fmt.Printf("  %-5d %-20s %-10s %-15.2f %d\n",
			c.ID, c.Name, currency, c.Price, c.SharesOutstanding)
	}
}
