package service

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

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

func InsertCompany(db *sql.DB, input model.CompanyInput) (int, error) {
	res, err := db.Exec(
		`INSERT INTO companies (name, shares_outstanding, price, currency_id) VALUES (?, ?, ?, ?)`,
		input.Name, input.SharesOutstanding, input.Price, input.CurrencyID,
	)
	if err != nil {
		return 0, err
	}
	id, err := res.LastInsertId()
	return int(id), err
}

func GetAllCompanies(db *sql.DB) ([]model.Company, error) {
	rows, err := db.Query(`
		SELECT c.id, c.name, c.shares_outstanding, c.price,
		       cu.id, cu.code, cu.name
		FROM companies c
		JOIN currencies cu ON c.currency_id = cu.id
		ORDER BY c.name
	`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var companies []model.Company
	for rows.Next() {
		var c model.Company
		var cu model.Currency
		if err := rows.Scan(
			&c.ID, &c.Name, &c.SharesOutstanding, &c.Price,
			&cu.ID, &cu.Code, &cu.Name,
		); err != nil {
			return nil, err
		}
		c.CurrencyID = cu.ID
		companies = append(companies, c)
	}
	return companies, rows.Err()
}
