-- v1.1.8 User Management — email verification tokens.
--
-- Created by `users::send_verification_email`; consumed by
-- `users::verify_email`. Same SHA-256 token-hash shape as
-- `app_user_sessions`. Single-use: the consume path is an atomic
-- UPDATE WHERE consumed_at IS NULL so a replayed token returns
-- "missing" the second time around without spurious side effects.

CREATE TABLE app_user_email_verifications (
    token_hash    TEXT PRIMARY KEY,
    app_id        UUID NOT NULL REFERENCES apps(id) ON DELETE CASCADE,
    user_id       UUID NOT NULL REFERENCES app_users(id) ON DELETE CASCADE,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    expires_at    TIMESTAMPTZ NOT NULL,
    consumed_at   TIMESTAMPTZ
);

CREATE INDEX idx_app_user_email_verifications_user
    ON app_user_email_verifications (app_id, user_id);
