package database

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

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

func GetCompanyBySymbol(db *sql.DB, symbol string) (*model.Company, error) {
	var c model.Company
	err := db.QueryRow(
		`SELECT id, symbol, shares_outstanding, price, currency_id FROM companies WHERE symbol = ?`,
		symbol,
	).Scan(&c.ID, &c.Symbol, &c.SharesOutstanding, &c.Price, &c.CurrencyID)

	if err == sql.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		return nil, fmt.Errorf("query company: %w", err)
	}
	return &c, nil
}

func GetCompanyByID(db *sql.DB, id int) (*model.Company, error) {
	var c model.Company
	err := db.QueryRow(
		`SELECT id, symbol, shares_outstanding, price, currency_id FROM companies WHERE id = ?`,
		id,
	).Scan(&c.ID, &c.Symbol, &c.SharesOutstanding, &c.Price, &c.CurrencyID)

	if err == sql.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		return nil, fmt.Errorf("query company: %w", err)
	}
	return &c, nil
}

func AddCompany(db *sql.DB, input model.CompanyInput) (int, error) {
	if input.CurrencyID == 0 {
		if input.CurrencyCode != "" {
			currency, err := GetCurrencyByCode(db, input.CurrencyCode)
			if err != nil {
				return 0, fmt.Errorf("could not get currency: %s", err)
			}
			input.CurrencyID = currency.ID
		} else {
			return 0, fmt.Errorf("no currency reference")
		}
	}

	res, err := db.Exec(
		`INSERT INTO companies (symbol, shares_outstanding, price, currency_id) VALUES (?, ?, ?, ?)`,
		input.Symbol, input.SharesOutstanding, input.Price, input.CurrencyID,
	)
	if err != nil {
		return 0, fmt.Errorf("failed to insert: %s", err)
	}
	id, err := res.LastInsertId()
	return int(id), err
}

func GetAllCompanies(db *sql.DB) ([]model.Company, error) {
	rows, err := db.Query(`
		SELECT id, symbol, shares_outstanding, price, currency_id FROM companies 
	`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

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