package operations

import (
	"database/sql"
	"sevenkeys/database/entities"
	"time"
)

func GetGamepieceByName(db *sql.DB, name string) (entities.Gamepiece, error) {
	var gamepiece entities.Gamepiece

	query := "SELECT Id, Name FROM Gamepiece WHERE Name = ?;"
	err := db.QueryRow(query, name).Scan(&gamepiece.Id, &gamepiece.Name)

	return gamepiece, err
}

func GetCacheTimestampByType(db *sql.DB, cacheType string) (time.Time, error) {
	var timestamp string

	query := "SELECT Stamp FROM CacheTimestamp WHERE CacheType = ?;"
	err := db.QueryRow(query, cacheType).Scan(&timestamp)

	if err == sql.ErrNoRows {
		return time.Unix(0, 0), nil
	}

	stamp, err := time.Parse("2006-01-02 15:04:05", timestamp)
	if err != nil {
		return time.Unix(0, 0), err
	}

	return stamp, err
}

func GetAllCardNames(db *sql.DB) ([]string, error) {
	var cardNames []string
	query := "SELECT Name FROM CardPrinting;"
	rows, err := db.Query(query)
	defer rows.Close()
	if err != nil {
		return cardNames, err
	}

	var cardName string
	for rows.Next() {
		err := rows.Scan(&cardName)
		if err != nil {
			return cardNames, err
		}

		cardNames = append(cardNames, cardName)
	}

	return cardNames, nil
}
