-- name: CreateDevice :one
INSERT INTO devices (
    user_id,
    device_token,
    platform
)
VALUES (
    $1, $2, $3
)
ON CONFLICT (user_id, device_token)
DO UPDATE SET
    is_active = true,
    last_seen = CURRENT_TIMESTAMP
RETURNING *;

-- name: GetUserDevices :many
SELECT *
FROM devices
WHERE user_id = $1 AND is_active = true;

-- name: UpdateDeviceLastSeen :exec
UPDATE devices
SET last_seen = CURRENT_TIMESTAMP
WHERE id = $1;

-- name: DeactivateDevice :exec
UPDATE devices
SET is_active = false
WHERE id = $1;

-- name: DeactivateUserDevices :exec
UPDATE devices
SET is_active = false
WHERE user_id = $1;

-- name: GetActiveDeviceTokens :many
SELECT device_token
FROM devices
WHERE user_id = $1 AND is_active = true AND platform IN ('android', 'ios');

-- name: DeactivateDeviceByToken :exec
UPDATE devices
SET is_active = false
WHERE user_id = $1 AND device_token = $2;