package database

import (
	"context"
	"time"

	"github.com/vingarcia/ksql"
)

func (d *Database) FindProductIDByBarcode(system string, barcode string) (id int, err error) {

	ctx := context.Background()

	err = d.db.QueryOne(ctx, &id, "SELECT id FROM products WHERE system = ? AND barcode = ?", system, barcode)
	if err == ksql.ErrRecordNotFound {
		return -1, nil
	}
	if err != nil {
		return -1, err
	}
	return
}

func (d *Database) CreateProduct(system string, barcode string) (*Product, error) {
	ctx := context.Background()
	var product = Product{
		System:     system,
		Barcode:    barcode,
		Created_at: time.Now(),
	}

	if err := d.db.Insert(ctx, ProductsTable, &product); err != nil {
		return nil, err
	}

	return &product, nil
}