package service

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

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

func InsertCurrency(db *sql.DB, input model.CurrencyInput) (int, error) {
	res, err := db.Exec(
		`INSERT INTO currencies (code, name) VALUES (?, ?)`,
		input.Code, input.Name,
	)
	if err != nil {
		return 0, err
	}
	id, err := res.LastInsertId()
	return int(id), err
}

func GetCurrencyByCode(db *sql.DB, code string) (*model.Currency, error) {
	c := &model.Currency{}
	err := db.QueryRow(
		`SELECT id, code, name FROM currencies WHERE code = ?`, code,
	).Scan(&c.ID, &c.Code, &c.Name)
	if err == sql.ErrNoRows {
		return nil, nil
	}
	return c, err
}

func GetAllCurrencies(db *sql.DB) ([]model.Currency, error) {
	rows, err := db.Query(`SELECT id, code, name FROM currencies ORDER BY code`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

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