-- devices: cdrop-managed devices (scan-login / native pairing). device_id is a
-- stable opaque cdrop-generated id that doubles as the session<->device join key
-- (passed to the broker as meta, echoed back as X-Auth-Meta on /verify). broker_sid
-- is the broker's session id, stored privately to revoke on device removal. tier is
-- a redundant cache of the broker scope (full/guest). name is human-readable and can
-- change without changing the device's identity (device_id is the key).
--
-- ASCII only: sqlc 1.31.x miscomputes byte offsets on multibyte comments and corrupts
-- every generated SQL const in the file. Keep this file pure ASCII.

-- CreateDevice records a device on scan-login collect / proxy-mint (or native pairing). Keyed
-- on device_id, so a re-pair with the same id refreshes the row (incl. the new broker_sid).
-- The WHERE on the upsert scopes the update to the owning user so a (cryptographically
-- impossible) cross-user device_id collision can never reassign the row owner; user_id is
-- immutable for a given device_id.
-- name: CreateDevice :exec
INSERT INTO devices (device_id, user_id, name, type, tier, broker_sid, created_at, last_seen)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (device_id) DO UPDATE SET
    name = excluded.name,
    type = excluded.type,
    tier = excluded.tier,
    broker_sid = excluded.broker_sid,
    last_seen = excluded.last_seen
WHERE devices.user_id = excluded.user_id;

-- TouchDevice refreshes last_seen + tier on each authenticated request. Update-only:
-- the row is created at collect time, so a missing row (e.g. a device authorized via
-- the broker's own device flow, not cdrop's) simply isn't cdrop-managed and no-ops.
-- name: TouchDevice :exec
UPDATE devices SET last_seen = ?, tier = ? WHERE device_id = ? AND user_id = ?;

-- name: ListDevicesByUser :many
SELECT device_id, user_id, name, type, tier, broker_sid, created_at, last_seen
FROM devices
WHERE user_id = ?
ORDER BY name;

-- name: GetDevice :one
SELECT device_id, user_id, name, type, tier, broker_sid, created_at, last_seen
FROM devices
WHERE device_id = ?;

-- name: DeleteDevice :execrows
DELETE FROM devices
WHERE device_id = ? AND user_id = ?;

-- name: RenameDevice :execrows
UPDATE devices SET name = ?
WHERE device_id = ? AND user_id = ?;

-- name: DeleteStaleDevices :exec
DELETE FROM devices
WHERE last_seen < ?;
