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

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

-- name: GetUserByAPIToken :one
SELECT * FROM users WHERE api_token = $1;

-- name: CountUsers :one
SELECT count(*) FROM users;

-- name: SetSubsonicPassword :exec
-- Stores (or clears with NULL) the per-user Subsonic legacy credential used
-- for t/s and p auth on /rest/*. Must be plaintext; see migration 0003.
UPDATE users SET subsonic_password = $2 WHERE id = $1;

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

-- name: SetListenBrainzToken :exec
UPDATE users
SET listenbrainz_token = $2,
    listenbrainz_enabled = CASE WHEN COALESCE($2, '') = '' THEN FALSE ELSE listenbrainz_enabled END
WHERE id = $1;

-- name: SetListenBrainzEnabled :exec
UPDATE users
SET listenbrainz_enabled = $2
WHERE id = $1;

-- name: GetListenBrainzConfig :one
-- Returns the user's LB token + enabled flag and the most recent
-- play_events.scrobbled_at for last-scrobbled-at status.
SELECT
    u.listenbrainz_token,
    u.listenbrainz_enabled,
    (SELECT MAX(pe.scrobbled_at)::timestamptz
     FROM play_events pe
     WHERE pe.user_id = u.id) AS last_scrobbled_at
FROM users u
WHERE u.id = $1;
