-- name: UpsertDevice :exec
INSERT INTO devices (user_id, name, type, last_seen)
VALUES (?, ?, ?, ?)
ON CONFLICT (user_id, name) DO UPDATE SET
    type = excluded.type,
    last_seen = excluded.last_seen;

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

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

-- DeleteOrphanBrowserDevices removes browser device rows with no live web_session
-- (the session was revoked or expired), keeping the device list aligned with the
-- session list. The ? is the current epoch second. Native (macos/windows/linux/ios)
-- and shortcut devices are left alone: they legitimately keep no web_session.
-- name: DeleteOrphanBrowserDevices :execrows
DELETE FROM devices
WHERE type = 'browser'
  AND NOT EXISTS (
    SELECT 1 FROM web_sessions ws
    WHERE ws.user_id = devices.user_id
      AND ws.device_name = devices.name
      AND ws.expires_at > ?
  );

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