-- push_subscriptions: Web Push and APNs subscription records.
-- id is hex SHA-256(endpoint/device-token), making upsert idempotent.
-- platform distinguishes 'webpush' (browser VAPID) from 'apns' (iOS device token).
-- Lookups are by (user_id, device_name, platform) so each channel only sees its own rows.
-- Dead endpoints (push service returns 404/410, APNs returns 410) are pruned by DeletePushSubscription.
-- NOTE: keep this file pure ASCII; sqlc v1.31.1 drifts byte offsets on
-- multibyte runes in query files, corrupting the generated SQL.

-- name: UpsertPushSubscription :exec
INSERT INTO push_subscriptions (id, user_id, device_name, endpoint, p256dh, auth, user_agent, locale, platform, created_at, last_used_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'webpush', ?, ?)
ON CONFLICT(id) DO UPDATE SET
    user_id      = excluded.user_id,
    device_name  = excluded.device_name,
    p256dh       = excluded.p256dh,
    auth         = excluded.auth,
    user_agent   = excluded.user_agent,
    locale       = excluded.locale,
    platform     = excluded.platform,
    last_used_at = excluded.last_used_at;

-- name: ListPushSubscriptionsByUserDevice :many
SELECT id, user_id, device_name, endpoint, p256dh, auth, user_agent, locale, platform, created_at, last_used_at
FROM push_subscriptions
WHERE user_id = ? AND device_name = ? AND platform = 'webpush';

-- name: ListAPNsSubscriptionsByUserDevice :many
SELECT id, user_id, device_name, endpoint, p256dh, auth, user_agent, locale, platform, created_at, last_used_at
FROM push_subscriptions
WHERE user_id = ? AND device_name = ? AND platform = 'apns';

-- name: UpsertAPNsSubscription :exec
INSERT INTO push_subscriptions (id, user_id, device_name, endpoint, p256dh, auth, user_agent, locale, platform, created_at, last_used_at)
VALUES (?, ?, ?, ?, '', '', '', ?, 'apns', ?, ?)
ON CONFLICT(id) DO UPDATE SET
    user_id      = excluded.user_id,
    device_name  = excluded.device_name,
    locale       = excluded.locale,
    platform     = excluded.platform,
    last_used_at = excluded.last_used_at;

-- name: TouchPushSubscription :exec
UPDATE push_subscriptions
SET last_used_at = ?
WHERE id = ?;

-- name: DeletePushSubscription :exec
DELETE FROM push_subscriptions
WHERE id = ?;

-- name: DeletePushSubscriptionsByUserDevice :exec
DELETE FROM push_subscriptions
WHERE user_id = ? AND device_name = ?;
