-- name: GetCompletedJobs :many
SELECT id,
	   startedTs,
	   completedTs,
	   targetSiteName,
	   auctionsFound,
	   errors
	FROM runner.scrapejob
	WHERE completedts is not null OR NOW() >= startedts + (30 ||' minutes')::interval
	ORDER BY startedTs DESC
	OFFSET (sqlc.arg(page)::INTEGER * sqlc.arg(pageSize)::INTEGER)
	LIMIT sqlc.arg(pageSize)::INTEGER;

-- name: GetActiveJobs :many
SELECT id,
	   startedTs,
	   completedTs,
	   targetSiteName,
	   auctionsFound,
	   errors
	FROM runner.scrapejob
	WHERE completedTs is null AND NOW() < startedTs + (30 ||' minutes')::interval
	ORDER BY startedTs DESC
	OFFSET (sqlc.arg(page)::INTEGER * sqlc.arg(pageSize)::INTEGER)
	LIMIT sqlc.arg(pageSize)::INTEGER;

-- name: GetJobCounts :one
SELECT COUNT(*) AS total,
       (SELECT COUNT(*) FROM runner.scrapejob
	   		WHERE completedts is not null OR NOW() >= startedts + (30 ||' minutes')::interval) AS completed,
       (SELECT COUNT(*) FROM runner.scrapejob
	   		WHERE completedts is null AND NOW() < startedts + (30 ||' minutes')::interval) AS active
	   FROM runner.scrapejob;

-- name: GetJobByID :one
SELECT id,
	   startedTs,
	   completedTs,
	   targetSiteName,
	   auctionsFound,
	   errors
	FROM runner.scrapejob
	WHERE id = $1;

-- name: CreateScrapeJob :one
INSERT INTO runner.scrapejob (
		targetSiteName
	) VALUES (
		$1
	) RETURNING *;


-- name: CompleteScrapeJob :exec
UPDATE runner.scrapejob SET
	completedTs = $2,
	auctionsFound = $3,
	errors = $4
WHERE id = $1;
