----------------------------------------------------------------------------------------------------
-- Keys; aka user sessions/auth tokens
----------------------------------------------------------------------------------------------------

-- name: migration-0000-create-user-keys#
-- Keys represent API keys and auth sessions
CREATE TABLE IF NOT EXISTS user_keys (
   id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(32))))
 , user_id INTEGER
 , name TEXT
 , expiration TEXT
);

-- name: create-key^
INSERT INTO user_keys (
   user_id
 , name
 , expiration
)
VALUES (:uid, :name, :expiration)
RETURNING
   id
 , user_id
;

-- name: try-login^
SELECT
   id
 , status_id
FROM users
WHERE
   ((name = :username AND hash = :hash)
   OR (email = :username AND hash = :hash))
   AND ((verified_at IS NOT NULL
         AND approved_at IS NOT NULL
         AND enabled_at IS NOT NULL)
        OR group_id = 0)
LIMIT 1
;

-- name: list-keys
SELECT
   id
 , name
 , expiration
FROM user_keys
WHERE
   user_id = :uid
;

-- name: list-nonweb-keys
SELECT
   id
 , name
 , expiration
FROM user_keys
WHERE
   user_id = :uid
   AND name NOT LIKE '%web session%'
;

-- name: fetch-key^
SELECT
   *
FROM user_keys
WHERE
   id = :kid
;

-- name: try-key^
SELECT
   k.id
 , user_id
FROM user_keys k
INNER JOIN users u
   ON k.user_id = u.id
WHERE
   (expiration IS NULL OR unixepoch(expiration) > unixepoch('now'))
   AND k.id = :kid
   AND (u.enabled_at IS NOT NULL -- and the user is not disabled!
        OR u.group_id = 0)       -- or the user is a root
;

-- name: refresh-key
UPDATE user_keys
SET
   expiration = :expiration
WHERE
   id = :kid
;

-- name: delete-key
DELETE FROM user_keys
WHERE
   user_id = :uid
   AND id = :kid
;
