-- name: CreateInvite :one
INSERT INTO user_invites (token, invited_by, note, expires_at)
VALUES ($1, $2, $3, $4)
RETURNING *;

-- name: GetInviteByToken :one
SELECT * FROM user_invites WHERE token = $1;

-- name: ListInvitesActive :many
-- Active = not redeemed and not expired. Used by the admin invites
-- panel as the primary list.
SELECT * FROM user_invites
 WHERE redeemed_at IS NULL AND expires_at > now()
 ORDER BY created_at DESC;

-- name: ListInvitesAll :many
-- Includes redeemed + expired for full audit visibility. Caller
-- supplies a LIMIT to bound the response.
SELECT * FROM user_invites
 ORDER BY created_at DESC
 LIMIT $1;

-- name: RedeemInvite :execrows
-- Atomic claim: returns rows-affected so the caller can detect
-- already-redeemed / expired tokens (rows=0) versus successful claim
-- (rows=1). Use this from the registration handler.
UPDATE user_invites
   SET redeemed_at = now(), redeemed_by = $2
 WHERE token = $1
   AND redeemed_at IS NULL
   AND expires_at > now();

-- name: DeleteInvite :exec
-- Admin-revoke. Only deletes unredeemed invites.
DELETE FROM user_invites WHERE token = $1 AND redeemed_at IS NULL;
