-- name: GetUserByID :one
SELECT * FROM users
WHERE id = $1;

-- name: GetUserByUsername :one
SELECT * FROM users
WHERE username = $1;

-- name: GetUsers :many
SELECT * FROM users;

-- name: CreateUser :one
INSERT INTO users (
		username,
		password,
		email,
		is_admin
	) VALUES ($1, $2, $3, $4)
RETURNING *;

-- name: DeleteUser :exec
DELETE FROM users WHERE username = $1;

-- name: UpdatePassword :exec
UPDATE users SET password = $2 WHERE username = $1;

-- name: UpdateUser :one
UPDATE users SET
	email = COALESCE(sqlc.narg('email'), email),
	is_admin = COALESCE(sqlc.narg('is_admin'), is_admin)
WHERE
	username = $1
RETURNING *;

-- name: CreateAPIKey :one
INSERT INTO api_keys(
	owner,
	created_at,
	expires,
	disabled,
	api_key
	) VALUES ($1, NOW(), $2, $3, gen_random_uuid())
RETURNING *;

-- name: DeleteAPIKey :exec
DELETE FROM api_keys WHERE api_key = $1;

-- name: GetAPIKey :one
SELECT
	a.id,
	a.owner,
	a.created_at,
	a.expires,
	a.disabled,
	a.api_key,
	u.username
FROM api_keys a
JOIN users u ON (a.owner = u.id)
WHERE api_key = $1;

-- name: GetAppPrefs :one
SELECT (prefs->>(@app_name::TEXT))::JSONB FROM users WHERE id = @uid;

-- name: SetAppPrefs :exec
UPDATE users SET prefs = COALESCE(prefs, '{}'::JSONB) || jsonb_build_object(@app_name::TEXT, @prefs::JSONB) WHERE id = @uid;
