-- name: GetUpcoming :many
SELECT
	ua.id,
	ua.fingerprint,
	ua.title,
	ua.description,
	ua.startts,
	ua.endts,
	ua.itemcount,
	ua.sourcesiteurl,
	ua.sourcesitename,
	ua.sourceurl,
	ua.country,
	ua.province
FROM catalog.upcoming_auctions ua
WHERE
	ua.endts >= DATE(NOW()) AND
	(case when sqlc.arg(searchTerm) = '' then
		ua.id > 0
	else
		ua.ts @@ websearch_to_tsquery(sqlc.arg(searchTerm))
	end)
ORDER BY
	ua.endts ASC,
	(case when sqlc.arg(searchTerm) != '' then
		ts_rank(ua.ts, websearch_to_tsquery(sqlc.arg(searchTerm)))
	end) DESC
OFFSET (sqlc.arg(page)::INTEGER * sqlc.arg(pageSize)::INTEGER)
LIMIT sqlc.arg(pageSize)::INTEGER;

-- name: GetTotals :one
SELECT COUNT(*) as total,
	   (SELECT COUNT(*) FROM catalog.upcoming_auctions ua
		WHERE
			ua.endts >= DATE(NOW()) AND
			(case when sqlc.arg(searchTerm) = '' then
				ua.id > 0
			else
				ua.ts @@ websearch_to_tsquery(sqlc.arg(searchTerm))
		end)) as found
FROM catalog.upcoming_auctions
WHERE endts >= DATE(NOW());

-- name: ImportAuction :one
SELECT catalog.bh_import_auction(
	sqlc.arg(fingerprint),
	sqlc.arg(title),
	sqlc.arg(startTs),
	sqlc.arg(endTs),
	sqlc.arg(description),
	sqlc.arg(itemCount),
	sqlc.arg(sourceSiteURL),
	sqlc.arg(sourceSiteName),
	sqlc.arg(sourceURL),
	sqlc.arg(country),
	sqlc.arg(province));
