CREATE TABLE user_mfa_settings (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id uuid NOT NULL UNIQUE REFERENCES users(id) ON DELETE RESTRICT,
    totp_secret_ciphertext text,
    totp_enabled boolean NOT NULL DEFAULT false,
    enabled_at timestamptz,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now(),
    CHECK (
        (totp_enabled = false)
        OR (totp_enabled = true AND totp_secret_ciphertext IS NOT NULL AND enabled_at IS NOT NULL)
    )
);

CREATE INDEX user_mfa_settings_totp_enabled_idx
    ON user_mfa_settings (totp_enabled);

CREATE TRIGGER user_mfa_settings_set_updated_at
BEFORE UPDATE ON user_mfa_settings
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
