package lista

import (
	"database/sql"
	"time"
)

type Producto struct {
	Id       int       `json:"id"`
	Fecha    time.Time `json:"fecha"`
	Nombre   string    `json:"nombre"`
	Cantidad int       `json:"cantidad"`
}

type DataWrapper struct {
	Productos []Producto `json:"productos"`
}

func InsertarProducto(db *sql.DB, p *Producto) (int64, error) {

	sql := `INSERT INTO productos (fecha,nombre,cantidad) VALUES (?, ?, ?);`

	resultado, err := db.Exec(sql, (*p).Fecha, p.Nombre, p.Cantidad)
	if err != nil {

		return 0, err

	}
	return resultado.LastInsertId()

}

func ActualizarProducto(db *sql.DB, id int, nombre string, cantidad int) (int64, error) {

	sql := `UPDATE productos SET nombre = ?, cantidad = ? WHERE id = ?;`
	resultado, err := db.Exec(sql, nombre, cantidad, id)
	if err != nil {

		return 0, err
	}
	return resultado.RowsAffected()

}

func EliminarProducto(db *sql.DB, id int) (int64, error) {

	sql := `DELETE FROM productos WHERE id = ?`
	resultado, err := db.Exec(sql, id)
	if err != nil {

		return 0, err
	}

	return resultado.RowsAffected()

}

func ObtenerLista(db *sql.DB) ([]Producto, error) {

	filas, err := db.Query("SELECT id, fecha, nombre, cantidad FROM productos")
	if err != nil {

		return nil, err

	}

	defer filas.Close()

	var productos []Producto

	for filas.Next() {
		var p Producto
		if err := filas.Scan(&p.Id, &p.Fecha, &p.Nombre, &p.Cantidad); err != nil {

			return nil, err

		}

		productos = append(productos, p)

	}
	return productos, filas.Err()
}
