package db

import "time"

func Session_UpdateLastSeenAt(
	tx TX,
	id string,
) (err error) {
	_, err = tx.Exec("UPDATE sessions SET LastSeenAt=? WHERE SessionID=?", time.Now().Unix(), id)
	return err
}

func Session_SetSignedIn(
	tx TX,
	id string,
) (err error) {
	_, err = tx.Exec("UPDATE sessions SET SignedIn=1 WHERE SessionID=?", id)
	return err
}

func Session_DeleteBefore(
	tx TX,
	timestamp int64,
) (err error) {
	_, err = tx.Exec("DELETE FROM sessions WHERE LastSeenAt<?", timestamp)
	return err
}

func Peer_ListAll(tx TX, networkID int64) ([]*Peer, error) {
	const query = Peer_SelectQuery + ` WHERE NetworkID=? ORDER BY PeerIP ASC`
	return Peer_List(tx, query, networkID)
}

func Peer_GetByAPIKey(tx TX, apiKey string) (*Peer, error) {
	return Peer_GetWhere(
		tx,
		Peer_SelectQuery+` WHERE APIKey=?`,
		apiKey)
}

func Peer_Exists(tx TX, networkID int64, ip byte) (exists bool, err error) {
	const query = `SELECT EXISTS(SELECT 1 FROM peers WHERE NetworkID=? AND PeerIP=?)`
	err = tx.QueryRow(query, networkID, ip).Scan(&exists)
	return
}
